Merge pull request #3226 from daboe01/CPLanguageModel-and-friends

New: CPSystemLanguageModel and CPLanguageModelSession
This commit is contained in:
daboe01
2026-08-26 20:48:59 +02:00
committed by GitHub
8 changed files with 1665 additions and 0 deletions
+615
View File
@@ -0,0 +1,615 @@
/*
* CPLanguageModel.j
* Foundation
*
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
@import "CPObject.j"
@import "CPString.j"
@import "CPError.j"
@import "CPDictionary.j"
@import "CPBundle.j"
@import "CPUserDefaults.j"
// File-scoped fallback configuration parameters
var CPLanguageModelSessionFallbackServiceType = @"ollama",
CPLanguageModelSessionFallbackEndpoint = @"http://localhost:11434/api/generate",
CPLanguageModelSessionFallbackModel = @"gemma4:e4b",
CPLanguageModelSessionFallbackAPIKey = @"",
CPLanguageModelSessionFallbackAPIKeyUserDefaultKey = @"",
CPLanguageModelSessionEndorsesFallback = NO;
/*!
@ingroup foundation
@class CPSystemLanguageModel
CPSystemLanguageModel provides a standard query interface to inspect the
availability of client-side, on-device large language models (such as Gemma Nano on Chrome)
in the active web browser runtime.
*/
@implementation CPSystemLanguageModel : CPObject
var sharedInstance = nil;
/*!
Returns the singleton system language model monitor.
@return the default CPSystemLanguageModel instance
*/
+ (id)defaultModel
{
if (!sharedInstance)
sharedInstance = [[CPSystemLanguageModel alloc] init];
return sharedInstance;
}
/*!
Asynchronously queries the active browser environment to determine if on-device
language models are supported and readily available to execute prompts.
@param completionHandler a callback block executed with a boolean parameter (supported)
*/
- (void)supportsLocaleWithCompletionHandler:(Function)completionHandler
{
if (typeof window === "undefined" || !completionHandler)
{
if (completionHandler)
completionHandler(NO);
return;
}
(async function() {
var supported = false;
try {
if (window.ai && window.ai.languageModel) {
// Pass language options to align with the creation options
var options = {
expectedInputs: [{ type: "text", languages: ["en"] }],
expectedOutputs: [{ type: "text", languages: ["en"] }]
};
if (typeof window.ai.languageModel.availability === 'function') {
var avail = await window.ai.languageModel.availability(options);
supported = (avail === "readily" || avail === "available" || avail === "after-download");
} else if (typeof window.ai.languageModel.capabilities === 'function') {
var caps = await window.ai.languageModel.capabilities(options);
supported = (caps.available === "readily" || caps.available === "after-download");
} else {
supported = true;
}
}
else if (window.LanguageModel) {
supported = true;
}
} catch (e) {
supported = false;
}
completionHandler(supported);
})();
}
@end
/*!
@ingroup foundation
@class CPLanguageModelSession
CPLanguageModelSession manages an active session with a local on-device
language model. If the active browser does not support on-device models, the session
gracefully and transparently falls back to configured remote server endpoints.
@discussion
CPLanguageModelSession handles text generation prompts. If on-device AI
(like Gemma Nano) is supported by the browser, it is utilized directly.
Otherwise, or if CPLanguageModelSessionEndorsesFallback is configured to YES,
the session automatically falls back to configured network-based providers
(such as local Ollama, Groq, or OpenRouter).
Fallback configurations can be populated globally using the application's Info.plist
via the following keys:
<pre>
CPEndorseLanguageModelFallback - YES to bypass on-device models and force fallback
CPDefaultLanguageModelService - "ollama" | "groq" | "gemini" | "openrouter"
CPDefaultLanguageModelEndpoint - API Endpoint (e.g. Ollama URL)
CPDefaultLanguageModelModel - Model name string
CPDefaultLanguageModelAPIKeyUserDefaultKey - CPUserDefaults key containing the actual API token
CPDefaultLanguageModelAPIKey - Authentication token string (Unsecure direct fallback)
</pre>
*/
@implementation CPLanguageModelSession : CPObject
{
id _chromeSession @accessors(property=chromeSession);
CPString _instructions @accessors(property=instructions);
CPString _fallbackServiceType @accessors(property=fallbackServiceType);
CPString _fallbackEndpoint @accessors(property=fallbackEndpoint);
CPString _fallbackModel @accessors(property=fallbackModel);
CPString _fallbackAPIKey @accessors(property=fallbackAPIKey);
}
/*!
Initializes fallback defaults and "Endorsement" flags from the application's Info.plist.
*/
+ (void)initialize
{
if (self === [CPLanguageModelSession class])
{
var bundle = [CPBundle mainBundle];
CPLanguageModelSessionEndorsesFallback = !![bundle objectForInfoDictionaryKey:@"CPEndorseLanguageModelFallback"];
CPLanguageModelSessionFallbackServiceType = [bundle objectForInfoDictionaryKey:@"CPDefaultLanguageModelService"] || @"ollama";
CPLanguageModelSessionFallbackEndpoint = [bundle objectForInfoDictionaryKey:@"CPDefaultLanguageModelEndpoint"] || @"http://localhost:11434/api/generate";
CPLanguageModelSessionFallbackModel = [bundle objectForInfoDictionaryKey:@"CPDefaultLanguageModelModel"] || @"gemma4:e4b";
CPLanguageModelSessionFallbackAPIKey = [bundle objectForInfoDictionaryKey:@"CPDefaultLanguageModelAPIKey"] || @"";
CPLanguageModelSessionFallbackAPIKeyUserDefaultKey = [bundle objectForInfoDictionaryKey:@"CPDefaultLanguageModelAPIKeyUserDefaultKey"] || @"";
}
}
/*!
Configures whether the session should bypass native browser AI models and force fallback network routing.
@param shouldEndorse YES to bypass native AI; NO to prioritize native AI if available
*/
+ (void)setEndorsesFallback:(BOOL)shouldEndorse
{
CPLanguageModelSessionEndorsesFallback = shouldEndorse;
}
/*!
Indicates if the session bypasses native browser AI models.
@return YES if forced fallback is active; NO otherwise
*/
+ (BOOL)endorsesFallback
{
return CPLanguageModelSessionEndorsesFallback;
}
/*!
Configures fallback details dynamically, overriding any defaults loaded from Info.plist.
@param serviceType the service type (e.g. @"ollama", @"groq", @"gemini", @"openrouter")
@param endpoint the network target URL
@param model the model identifier
@param apiKey the API key string
*/
+ (void)setFallbackServiceType:(CPString)serviceType endpoint:(CPString)endpoint model:(CPString)model apiKey:(CPString)apiKey
{
CPLanguageModelSessionFallbackServiceType = serviceType;
CPLanguageModelSessionFallbackEndpoint = endpoint;
CPLanguageModelSessionFallbackModel = model;
CPLanguageModelSessionFallbackAPIKey = apiKey;
}
/*!
Configures the CPUserDefaults key used to dynamically look up the API key.
@param keyName the user defaults key name containing the actual credentials
*/
+ (void)setFallbackAPIKeyUserDefaultKey:(CPString)keyName
{
CPLanguageModelSessionFallbackAPIKeyUserDefaultKey = keyName;
}
/*!
Gets the CPUserDefaults key name used to dynamically look up the API key.
@return the user defaults key name
*/
+ (CPString)fallbackAPIKeyUserDefaultKey
{
return CPLanguageModelSessionFallbackAPIKeyUserDefaultKey;
}
/*!
Initializes a language model session with specific system instructions.
@param instructions the system instructions or context prompt
@return the initialized session
*/
- (id)initWithInstructions:(CPString)instructions
{
self = [super init];
if (self)
{
_instructions = instructions;
_chromeSession = nil;
_fallbackServiceType = nil;
_fallbackEndpoint = nil;
_fallbackModel = nil;
_fallbackAPIKey = nil;
}
return self;
}
/*!
Initializes a language model session with specific system instructions and an explicit programmatic API key.
@param instructions the system instructions or context prompt
@param apiKey the fallback API key to use specifically for this session
@return the initialized session
*/
- (id)initWithInstructions:(CPString)instructions apiKey:(CPString)apiKey
{
self = [self initWithInstructions:instructions];
if (self)
{
_fallbackAPIKey = apiKey;
}
return self;
}
/*!
Initializes a language model session with instructions and explicit fallback settings.
@param instructions the system instructions or context prompt
@param options dictionary containing custom fallback configuration (e.g. @{ @"serviceType": ..., @"apiKey": ... })
@return the initialized session
*/
- (id)initWithInstructions:(CPString)instructions fallbackOptions:(CPDictionary)options
{
self = [self initWithInstructions:instructions];
if (self)
{
if (options)
{
_fallbackServiceType = [options objectForKey:@"serviceType"];
_fallbackEndpoint = [options objectForKey:@"endpoint"];
_fallbackModel = [options objectForKey:@"model"];
_fallbackAPIKey = [options objectForKey:@"apiKey"];
}
}
return self;
}
/*!
Sends a query prompt to the language model session.
@param prompt the query text to analyze
@param completionHandler a callback receiving the response string or a CPError instance
*/
- (void)respondToPrompt:(CPString)prompt options:(id)options completionHandler:(Function)completionHandler
{
// If the developer forced fallback, bypass native browser execution
if (CPLanguageModelSessionEndorsesFallback)
{
[self _executeRemoteFallbackWithPrompt:prompt options:options completionHandler:completionHandler];
return;
}
if (_chromeSession)
{
[self _executePrompt:prompt options:options completionHandler:completionHandler];
return;
}
var instructions = [self instructions];
[CPLanguageModelSession _getChromeFactoryWithCompletionHandler:function(factory, error) {
if (error) {
[self _executeRemoteFallbackWithPrompt:prompt options:options completionHandler:completionHandler];
return;
}
// Add the required expected input and output parameters
var sessionOptions = {
expectedInputs: [{ type: "text", languages: ["en"] }],
expectedOutputs: [{ type: "text", languages: ["en"] }]
};
if (instructions) {
sessionOptions.systemPrompt = instructions;
}
factory.create(sessionOptions).then(function(session) {
[self setChromeSession:session];
[self _executePrompt:prompt options:options completionHandler:completionHandler];
}).catch(function(err) {
[self _executeRemoteFallbackWithPrompt:prompt options:options completionHandler:completionHandler];
});
}];
}
/*!
Sends a query prompt and streams the response chunk-by-chunk for live UI rendering.
@param prompt the query text to analyze
@param chunkHandler a callback block executed as text increments are received
@param completionHandler a final callback block executed when generation completes
*/
- (void)respondToPrompt:(CPString)prompt
onChunkReceived:(Function)chunkHandler
completed:(Function)completionHandler
{
if (CPLanguageModelSessionEndorsesFallback)
{
[self _executeRemoteFallbackWithPrompt:prompt options:nil completionHandler:function(res, err) {
if (!err && chunkHandler)
chunkHandler(res);
completionHandler(res, err);
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode]; // pump run loop to force GUI update
}];
return;
}
if (_chromeSession)
{
[self _executePromptStreaming:prompt onChunkReceived:chunkHandler completed:completionHandler];
return;
}
var instructions = [self instructions];
[CPLanguageModelSession _getChromeFactoryWithCompletionHandler:function(factory, error) {
if (error) {
[self _executeRemoteFallbackWithPrompt:prompt options:nil completionHandler:function(res, err) {
if (!err && chunkHandler)
chunkHandler(res);
completionHandler(res, err);
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode]; // pump run loop to force GUI update
}];
return;
}
// Add the required expected input and output parameters
var options = {
expectedInputs: [{ type: "text", languages: ["en"] }],
expectedOutputs: [{ type: "text", languages: ["en"] }]
};
if (instructions)
options.systemPrompt = instructions;
factory.create(options).then(function(session) {
[self setChromeSession:session];
[self _executePromptStreaming:prompt onChunkReceived:chunkHandler completed:completionHandler];
}).catch(function(err)
{
[self _executeRemoteFallbackWithPrompt:prompt options:nil completionHandler:function(res, err) {
if (!err && chunkHandler)
chunkHandler(res);
completionHandler(res, err);
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode]; // pump run loop to force GUI update
}];
});
}];
}
/*!
Closes the session and releases associated memory resources on-device.
*/
- (void)destroy
{
if (_chromeSession && typeof _chromeSession.destroy === "function")
{
_chromeSession.destroy();
_chromeSession = nil;
}
}
// MARK: - Private Helper Methods
+ (void)_getChromeFactoryWithCompletionHandler:(Function)completionHandler
{
if (typeof window === "undefined")
{
var cpError = [CPError errorWithDomain:@"CPLanguageModelErrorDomain" code:-1 userInfo:[CPDictionary dictionaryWithObject:@"Execution environment is not a browser window." forKey:CPLocalizedDescriptionKey]];
completionHandler(nil, cpError);
return;
}
if (window.ai && window.ai.languageModel)
completionHandler(window.ai.languageModel, nil);
else if (window.LanguageModel)
completionHandler(window.LanguageModel, nil);
else
completionHandler(nil, [CPError errorWithDomain:@"CPLanguageModelErrorDomain" code:0 userInfo:nil]);
}
- (void)_executePrompt:(CPString)prompt options:(id)options completionHandler:(Function)completionHandler
{
var promptPromise = options ? _chromeSession.prompt(prompt, options) : _chromeSession.prompt(prompt);
promptPromise.then(function(result) {
completionHandler(result, nil);
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode]; // pump run loop to force GUI update
}).catch(function(err) {
var cpError = [CPError errorWithDomain:@"CPLanguageModelErrorDomain"
code:2
userInfo:[CPDictionary dictionaryWithObject:err.message forKey:CPLocalizedDescriptionKey]];
completionHandler(nil, cpError);
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode]; // pump run loop to force GUI update
});
}
- (CPString)_resolvedFallbackServiceType
{
return _fallbackServiceType || CPLanguageModelSessionFallbackServiceType;
}
- (CPString)_resolvedFallbackEndpoint
{
return _fallbackEndpoint || CPLanguageModelSessionFallbackEndpoint;
}
- (CPString)_resolvedFallbackModel
{
return _fallbackModel || CPLanguageModelSessionFallbackModel;
}
- (CPString)_resolvedFallbackAPIKey
{
// 1. Session instance explicit key has highest priority
if (_fallbackAPIKey)
return _fallbackAPIKey;
// 2. Class fallback API key set programmatically takes second priority
if (CPLanguageModelSessionFallbackAPIKey)
return CPLanguageModelSessionFallbackAPIKey;
// 3. Dynamic lookup from standard user defaults takes final priority
if (CPLanguageModelSessionFallbackAPIKeyUserDefaultKey)
{
var defaults = [CPUserDefaults standardUserDefaults],
apiKey = [defaults objectForKey:CPLanguageModelSessionFallbackAPIKeyUserDefaultKey];
if (apiKey)
return apiKey;
}
return @"";
}
- (void)_executeRemoteFallbackWithPrompt:(CPString)prompt options:(id)options completionHandler:(Function)completionHandler
{
var systemPrompt = [self instructions],
serviceType = [self _resolvedFallbackServiceType],
endpoint = [self _resolvedFallbackEndpoint],
model = [self _resolvedFallbackModel],
apiKey = [self _resolvedFallbackAPIKey];
var reqUrl = @"",
headers = { "Content-Type": "application/json" },
payload = {};
if (serviceType === @"groq")
{
reqUrl = "https://api.groq.com/openai/v1/chat/completions";
headers["Authorization"] = "Bearer " + apiKey;
payload = {
"model": model,
"messages": [
{ "role": "system", "content": systemPrompt },
{ "role": "user", "content": prompt }
],
"temperature": 0
};
}
else if (serviceType === @"gemini")
{
reqUrl = "https://generativelanguage.googleapis.com/v1beta/models/" + model + ":generateContent?key=" + apiKey;
payload = {
"contents": [
{ "parts": [{ "text": systemPrompt + "\n\n" + prompt }] }
],
"generationConfig": { "temperature": 0 }
};
}
else if (serviceType === @"openrouter")
{
reqUrl = "https://openrouter.ai/api/v1/chat/completions";
headers["Authorization"] = "Bearer " + apiKey;
payload = {
"model": model,
"messages": [
{ "role": "system", "content": systemPrompt },
{ "role": "user", "content": prompt }
],
"temperature": 0
};
}
else
{
reqUrl = endpoint || "http://localhost:11434/api/generate";
payload = {
"model": model,
"prompt": systemPrompt + "\n\n" + prompt,
"stream": false,
"options": { "temperature": 0 }
};
}
fetch(reqUrl, {
method: 'POST',
headers: headers,
body: JSON.stringify(payload)
})
.then(function(response) {
if (!response.ok) {
throw new Error("HTTP error! Status: " + response.status);
}
return response.json();
})
.then(function(data) {
var responseText = "";
if (serviceType === "groq" || serviceType === "openrouter") {
responseText = (data.choices && data.choices[0] && data.choices[0].message) ? data.choices[0].message.content : "";
} else if (serviceType === "gemini") {
responseText = (data.candidates && data.candidates[0] && data.candidates[0].content && data.candidates[0].content.parts) ? data.candidates[0].content.parts[0].text : "";
} else {
responseText = data.response || "";
}
completionHandler(responseText, nil);
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode]; // pump run loop to force GUI update
})
.catch(function(err) {
var cpError = [CPError errorWithDomain:@"CPLanguageModelErrorDomain"
code:4
userInfo:[CPDictionary dictionaryWithObject:err.message forKey:CPLocalizedDescriptionKey]];
completionHandler(nil, cpError);
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode]; // pump run loop to force GUI update
});
}
- (void)_executePromptStreaming:(CPString)prompt
onChunkReceived:(Function)chunkHandler
completed:(Function)completionHandler
{
var stream;
try {
stream = _chromeSession.promptStreaming(prompt);
} catch (err) {
var cpError = [CPError errorWithDomain:@"CPLanguageModelErrorDomain"
code:3
userInfo:[CPDictionary dictionaryWithObject:err.message forKey:CPLocalizedDescriptionKey]];
completionHandler(nil, cpError);
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode]; // pump run loop to force GUI update
return;
}
(async function() {
var lastChunk = "";
try {
for await (const chunk of stream) {
lastChunk = chunk;
if (chunkHandler) {
chunkHandler(chunk);
}
}
if (completionHandler)
{
completionHandler(lastChunk, nil);
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode]; // pump run loop to force GUI update
}
} catch (err) {
if (completionHandler) {
var cpError = [CPError errorWithDomain:@"CPLanguageModelErrorDomain"
code:2
userInfo:[CPDictionary dictionaryWithObject:err.message forKey:CPLocalizedDescriptionKey]];
completionHandler(nil, cpError);
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode]; // pump run loop to force GUI update
}
}
})();
}
@end
@@ -0,0 +1,657 @@
// AppController.j
// Manual test application for CPLanguageModelSession & CPSystemLanguageModel
// With custom SpeechBubbleBox drawing and editable System Prompt controls.
//
@import <AppKit/AppKit.j>
@import <Foundation/CPObject.j>
@import <Foundation/CPLanguageModel.j>
// --- SUBCLASS: SPEECH BUBBLE VIEW ---
@implementation SpeechBubbleBox : CPView
{
BOOL _isUser;
CPColor _bubbleColor;
}
- (id)initWithFrame:(CGRect)aFrame isUser:(BOOL)isUser fillColor:(CPColor)aColor
{
self = [super initWithFrame:aFrame];
if (self) {
_isUser = isUser;
_bubbleColor = aColor;
[self setAutoresizingMask:CPViewWidthSizable];
}
return self;
}
- (void)drawRect:(CGRect)aRect
{
var context = [[CPGraphicsContext currentContext] graphicsPort];
var bounds = [self bounds];
var w = CGRectGetWidth(bounds);
var h = CGRectGetHeight(bounds) - 10.0; // 10px spacing for the bottom triangle pointer
var r = 6.0; // Corner radius
var th = 10.0; // Tail height
// --- 1. FILL PATH ---
CGContextBeginPath(context);
// Top-left
CGContextMoveToPoint(context, r, 0);
// Top edge
CGContextAddLineToPoint(context, w - r, 0);
CGContextAddArcToPoint(context, w, 0, w, r, r);
// Right edge
CGContextAddLineToPoint(context, w, h - r);
CGContextAddArcToPoint(context, w, h, w - r, h, r);
// Bottom edge with triangular tail (RHS vs LHS)
if (_isUser) {
CGContextAddLineToPoint(context, w - 21, h);
CGContextAddLineToPoint(context, w - 21, h + th);
CGContextAddLineToPoint(context, w - 35, h);
CGContextAddLineToPoint(context, r, h);
} else {
CGContextAddLineToPoint(context, 35, h);
CGContextAddLineToPoint(context, 21, h + th);
CGContextAddLineToPoint(context, 21, h);
CGContextAddLineToPoint(context, r, h);
}
// Left edge
CGContextAddArcToPoint(context, 0, h, 0, h - r, r);
CGContextAddLineToPoint(context, 0, r);
CGContextAddArcToPoint(context, 0, 0, r, 0, r);
CGContextClosePath(context);
// Fill path
CGContextSetFillColor(context, _bubbleColor);
CGContextFillPath(context);
// --- 2. OUTLINE PATH ---
CGContextBeginPath(context);
CGContextMoveToPoint(context, r, 0);
CGContextAddLineToPoint(context, w - r, 0);
CGContextAddArcToPoint(context, w, 0, w, r, r);
CGContextAddLineToPoint(context, w, h - r);
CGContextAddArcToPoint(context, w, h, w - r, h, r);
if (_isUser) {
CGContextAddLineToPoint(context, w - 21, h);
CGContextAddLineToPoint(context, w - 21, h + th);
CGContextAddLineToPoint(context, w - 35, h);
CGContextAddLineToPoint(context, r, h);
} else {
CGContextAddLineToPoint(context, 35, h);
CGContextAddLineToPoint(context, 21, h + th);
CGContextAddLineToPoint(context, 21, h);
CGContextAddLineToPoint(context, r, h);
}
CGContextAddArcToPoint(context, 0, h, 0, h - r, r);
CGContextAddLineToPoint(context, 0, r);
CGContextAddArcToPoint(context, 0, 0, r, 0, r);
CGContextClosePath(context);
// Stroke outline
CGContextSetStrokeColor(context, [CPColor colorWithWhite:0.8 alpha:1.0]);
CGContextSetLineWidth(context, 1.0);
CGContextStrokePath(context);
}
@end
// --- MAIN CONTROLLER ---
@implementation AppController : CPObject
{
CPWindow _mainWindow;
CPScrollView _chatScrollView;
CPView _chatDocumentView;
CPTextField _chatInputField;
CPButton _chatSendButton;
CPButton _settingsButton;
CPCheckBox _forceFallbackCheckbox;
CPTextField _statusLabel;
CPTextView _systemPromptTextView;
CPWindow _settingsWindow;
CPPopUpButton _servicePopUp;
CPTextField _endpointField;
CPTextField _modelField;
CPTextField _apiKeyField;
CPLanguageModelSession _session;
float _currentChatY;
id _currentStreamingTextView;
CPProgressIndicator _currentSpinner;
}
- (void)applicationDidFinishLaunching:(CPNotification)aNotification
{
// Initialize default test settings in local user defaults
var defaults = [CPUserDefaults standardUserDefaults];
var defaultSettings = [CPDictionary dictionaryWithObjects:[
@"ollama",
@"http://localhost:11434/api/generate",
@"gemma4:e4b",
@""
] forKeys:[
@"LLMTestServiceType",
@"LLMTestEndpoint",
@"LLMTestModel",
@"LLMTestAPIKey"
]];
[defaults registerDefaults:defaultSettings];
// Read values to apply fallback routing to CPLanguageModelSession
var activeService = [defaults objectForKey:@"LLMTestServiceType"],
endpoint = [defaults objectForKey:@"LLMTestEndpoint"],
model = [defaults objectForKey:@"LLMTestModel"],
apiKey = [defaults objectForKey:@"LLMTestAPIKey"];
[CPLanguageModelSession setFallbackServiceType:activeService
endpoint:endpoint
model:model
apiKey:apiKey];
// Main manual test window setup
_mainWindow = [[CPWindow alloc] initWithContentRect:CGRectMake(0, 0, 800, 650)
styleMask:CPTitledWindowMask | CPClosableWindowMask | CPMiniaturizableWindowMask | CPResizableWindowMask];
[_mainWindow setTitle:@"CPLanguageModel Manual Test Tool"];
[_mainWindow center];
var contentView = [_mainWindow contentView];
var bounds = [contentView bounds];
// --- TOP CONTROL PANEL (Height 135px) ---
var topBar = [[CPView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(bounds), 135)];
[topBar setAutoresizingMask:CPViewWidthSizable | CPViewMaxYMargin];
[topBar setBackgroundColor:[CPColor colorWithWhite:0.92 alpha:1.0]];
[contentView addSubview:topBar];
_statusLabel = [[CPTextField alloc] initWithFrame:CGRectMake(15, 12, 300, 20)];
[_statusLabel setStringValue:@"Checking capability..."];
[_statusLabel setFont:[CPFont systemFontOfSize:12.0]];
[topBar addSubview:_statusLabel];
_forceFallbackCheckbox = [[CPCheckBox alloc] initWithFrame:CGRectMake(330, 12, 140, 20)];
[_forceFallbackCheckbox setTitle:@"Force Fallback"];
[_forceFallbackCheckbox setTarget:self];
[_forceFallbackCheckbox setAction:@selector(toggleForceFallback:)];
[topBar addSubview:_forceFallbackCheckbox];
_settingsButton = [[CPButton alloc] initWithFrame:CGRectMake(CGRectGetWidth(bounds) - 210, 9, 90, 26)];
[_settingsButton setTitle:@"Settings..."];
[_settingsButton setAutoresizingMask:CPViewMinXMargin];
[_settingsButton setTarget:self];
[_settingsButton setAction:@selector(openSettingsSheet:)];
[topBar addSubview:_settingsButton];
var clearButton = [[CPButton alloc] initWithFrame:CGRectMake(CGRectGetWidth(bounds) - 110, 9, 95, 26)];
[clearButton setTitle:@"Clear Chat"];
[clearButton setAutoresizingMask:CPViewMinXMargin];
[clearButton setTarget:self];
[clearButton setAction:@selector(clearChatAction:)];
[topBar addSubview:clearButton];
// System Prompt Header & Field [1]
var promptLabel = [[CPTextField alloc] initWithFrame:CGRectMake(15, 42, 300, 18)];
[promptLabel setStringValue:@"System Instructions (Persona):"];
[promptLabel setFont:[CPFont boldSystemFontOfSize:11.0]];
[promptLabel setTextColor:[CPColor darkGrayColor]];
[topBar addSubview:promptLabel];
var promptScroll = [[CPScrollView alloc] initWithFrame:CGRectMake(15, 62, CGRectGetWidth(bounds) - 30, 60)];
[promptScroll setAutoresizingMask:CPViewWidthSizable];
[promptScroll setAutohidesScrollers:YES];
_systemPromptTextView = [[CPTextView alloc] initWithFrame:[promptScroll bounds]];
[_systemPromptTextView setAutoresizingMask:CPViewWidthSizable | CPViewHeightSizable];
[_systemPromptTextView setEditable:YES];
[_systemPromptTextView setFont:[CPFont systemFontOfSize:11.0]];
// Default instruction preset [1]
[_systemPromptTextView setString:@"You are a helpful, concise testing assistant. You structure your explanations clearly using lists where appropriate."];
[promptScroll setDocumentView:_systemPromptTextView];
[topBar addSubview:promptScroll];
// --- SCROLLING CHAT CONTAINER ---
var scrollHeight = CGRectGetHeight(bounds) - 195;
_chatScrollView = [[CPScrollView alloc] initWithFrame:CGRectMake(0, 135, CGRectGetWidth(bounds), scrollHeight)];
[_chatScrollView setAutoresizingMask:CPViewWidthSizable | CPViewHeightSizable];
[_chatScrollView setAutohidesScrollers:YES];
[_chatScrollView setHasHorizontalScroller:NO];
[_chatScrollView setBackgroundColor:[CPColor whiteColor]];
_chatDocumentView = [[CPView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([_chatScrollView bounds]), scrollHeight)];
[_chatDocumentView setAutoresizingMask:CPViewWidthSizable];
[_chatScrollView setDocumentView:_chatDocumentView];
[contentView addSubview:_chatScrollView];
// --- INPUT CONTAINER ---
var bottomBarY = CGRectGetHeight(bounds) - 60;
var bottomBar = [[CPView alloc] initWithFrame:CGRectMake(0, bottomBarY, CGRectGetWidth(bounds), 60)];
[bottomBar setAutoresizingMask:CPViewWidthSizable | CPViewMinYMargin];
[bottomBar setBackgroundColor:[CPColor colorWithWhite:0.95 alpha:1.0]];
[contentView addSubview:bottomBar];
_chatInputField = [[CPTextField alloc] initWithFrame:CGRectMake(15, 13, CGRectGetWidth(bounds) - 130, 34)];
[_chatInputField setAutoresizingMask:CPViewWidthSizable];
[_chatInputField setEditable:YES];
[_chatInputField setBezeled:YES];
[_chatInputField setPlaceholderString:@"Type a prompt and press Enter..."];
[_chatInputField setTarget:self];
[_chatInputField setAction:@selector(submitPromptAction:)];
[bottomBar addSubview:_chatInputField];
_chatSendButton = [[CPButton alloc] initWithFrame:CGRectMake(CGRectGetWidth(bounds) - 105, 13, 90, 34)];
[_chatSendButton setTitle:@"Send"];
[_chatSendButton setAutoresizingMask:CPViewMinXMargin];
[_chatSendButton setTarget:self];
[_chatSendButton setAction:@selector(submitPromptAction:)];
[bottomBar addSubview:_chatSendButton];
[_mainWindow orderFront:self];
[self checkModelSupport];
[self resetSession];
}
- (void)checkModelSupport
{
var systemModel = [CPSystemLanguageModel defaultModel];
[_statusLabel setStringValue:@"Checking capability..."];
[systemModel supportsLocaleWithCompletionHandler:function(supported) {
if (supported)
[_statusLabel setStringValue:@"On-Device LLM: Supported"];
else
[_statusLabel setStringValue:@"On-Device LLM: Not available. Using fallback."];
}];
}
- (void)toggleForceFallback:(id)sender
{
var force = [sender state] === CPOnState;
[CPLanguageModelSession setEndorsesFallback:force];
[_statusLabel setStringValue:(force ? @"Fallback forced programmatically." : @"Prioritizing on-device model.")];
}
- (void)clearChatAction:(id)sender
{
[self resetSession];
}
- (void)resetSession
{
_currentChatY = 15;
_currentStreamingTextView = nil;
if (_currentSpinner) {
[_currentSpinner stopAnimation:self];
[_currentSpinner removeFromSuperview];
_currentSpinner = nil;
}
if (_session) {
[_session destroy];
}
// Read the custom instructions from the text field upon starting a fresh session [1]
var instructions = [_systemPromptTextView string] || @"";
_session = [[CPLanguageModelSession alloc] initWithInstructions:instructions];
[[_chatDocumentView subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
[_chatDocumentView setFrameSize:CGSizeMake(CGRectGetWidth([_chatScrollView bounds]), CGRectGetHeight([_chatScrollView bounds]))];
[self appendMessage:@"Session initialized.\n\nEnter a query below to begin." isUser:NO];
}
- (void)appendMessage:(CPString)text isUser:(BOOL)isUser
{
var docWidth = CGRectGetWidth([_chatScrollView bounds]) - 50;
var spinner = nil;
var textX = 15;
// Erstelle den Spinner, falls die Generierung beginnt
if (!isUser && [text isEqualToString:@"Generating response..."]) {
spinner = [[CPProgressIndicator alloc] initWithFrame:CGRectMake(15, 12, 16, 16)];
[spinner setStyle:CPProgressIndicatorSpinningStyle];
[spinner setControlSize:CPSmallControlSize];
[spinner setIndeterminate:YES];
[spinner startAnimation:self];
_currentSpinner = spinner;
textX = 38; // Verschiebe den Text nach rechts, um Platz für den Spinner zu schaffen
}
var textView = [[CPTextView alloc] initWithFrame:CGRectMake(textX, 10, docWidth - 15 - textX, 20)];
[textView setEditable:YES];
[textView setRichText:YES];
[textView setSelectable:YES];
[textView setBackgroundColor:[CPColor clearColor]];
[textView setAutoresizingMask:CPViewWidthSizable];
[textView setVerticallyResizable:YES];
[textView setHorizontallyResizable:NO];
[[textView textContainer] setWidthTracksTextView:YES];
var textHeight = 20;
var layoutManager = [textView layoutManager];
var textContainer = [textView textContainer];
try {
var parsedAttrStr = [CPMarkdownParser attributedStringFromMarkdown:text];
[textView insertText:parsedAttrStr];
var usedRect = [layoutManager usedRectForTextContainer:textContainer];
textHeight = CGRectGetHeight(usedRect);
if (textHeight < 20) {
textHeight = 20;
}
}
catch (e)
{
// Fallback bei Parsing-Fehler
console.error("Markdown append failure: ", e);
[textView setString:text];
[textView sizeToFit];
textHeight = CGRectGetHeight([textView frame]);
}
var cardHeight = textHeight + 20;
var bubbleHeight = cardHeight + 10;
var fillColor = isUser ? [CPColor colorWithRed:0.90 green:0.93 blue:1.0 alpha:1.0] : [CPColor colorWithWhite:0.96 alpha:1.0];
var cardBox = [[SpeechBubbleBox alloc] initWithFrame:CGRectMake(15, _currentChatY, docWidth, bubbleHeight)
isUser:isUser
fillColor:fillColor];
if (spinner) {
[cardBox addSubview:spinner];
}
[cardBox addSubview:textView];
[_chatDocumentView addSubview:cardBox];
if (!isUser) {
_currentStreamingTextView = textView;
}
_currentChatY += bubbleHeight + 15;
[_chatDocumentView setFrameSize:CGSizeMake(CGRectGetWidth([_chatScrollView bounds]), _currentChatY + 20)];
var boundsHeight = CGRectGetHeight([_chatScrollView bounds]);
if (_currentChatY > boundsHeight) {
[[_chatScrollView contentView] scrollToPoint:CGPointMake(0, _currentChatY - boundsHeight + 40)];
}
}
- (void)updateMessage:(CPString)newText
{
if (!_currentStreamingTextView)
return;
// Falls ein aktiver Spinner läuft, stoppe und entferne ihn, und richte das Textfeld wieder links aus
if (_currentSpinner) {
[_currentSpinner stopAnimation:self];
[_currentSpinner removeFromSuperview];
_currentSpinner = nil;
var docWidth = CGRectGetWidth([_chatScrollView bounds]) - 50;
[_currentStreamingTextView setFrame:CGRectMake(15, 10, docWidth - 30, CGRectGetHeight([_currentStreamingTextView frame]))];
}
try {
// 1. Text über Standard-Zuweisung neu setzen
var parsedAttrStr = [CPMarkdownParser attributedStringFromMarkdown:newText];
[_currentStreamingTextView setEditable:YES];
[_currentStreamingTextView setString:@""];
[_currentStreamingTextView insertText:parsedAttrStr];
[_currentStreamingTextView setEditable:NO];
var layoutManager = [_currentStreamingTextView layoutManager];
var textContainer = [_currentStreamingTextView textContainer];
var usedRect = [layoutManager usedRectForTextContainer:textContainer];
var textHeight = CGRectGetHeight(usedRect);
if (textHeight < 20)
textHeight = 20;
var cardHeight = textHeight + 20;
var bubbleHeight = cardHeight + 10;
var container = [_currentStreamingTextView superview];
if (container)
{
var oldBubbleHeight = CGRectGetHeight([container frame]);
[container setFrameSize:CGSizeMake(CGRectGetWidth([container frame]), bubbleHeight)];
[_currentStreamingTextView setFrameSize:CGSizeMake(CGRectGetWidth([_currentStreamingTextView frame]), textHeight)];
[container setNeedsDisplay:YES];
[_currentStreamingTextView setNeedsDisplay:YES];
var diffHeight = bubbleHeight - oldBubbleHeight;
_currentChatY += diffHeight;
}
}
catch (e)
{
console.error("Markdown rendering failure: ", e);
[_currentStreamingTextView setEditable:YES];
[_currentStreamingTextView setString:newText];
[_currentStreamingTextView setEditable:NO];
[_currentStreamingTextView sizeToFit];
var textHeight = CGRectGetHeight([_currentStreamingTextView frame]);
var container = [_currentStreamingTextView superview];
if (container) {
var oldBubbleHeight = CGRectGetHeight([container frame]);
var bubbleHeight = textHeight + 30;
[container setFrameSize:CGSizeMake(CGRectGetWidth([container frame]), bubbleHeight)];
[container setNeedsDisplay:YES];
var diffHeight = bubbleHeight - oldBubbleHeight;
_currentChatY += diffHeight;
}
}
[_chatDocumentView setFrameSize:CGSizeMake(CGRectGetWidth([_chatScrollView bounds]), _currentChatY + 20)];
var boundsHeight = CGRectGetHeight([_chatScrollView bounds]);
if (_currentChatY > boundsHeight)
[[_chatScrollView contentView] scrollToPoint:CGPointMake(0, _currentChatY - boundsHeight + 40)];
}
- (void)submitPromptAction:(id)sender
{
var prompt = [_chatInputField stringValue];
if (!prompt || [prompt stringByTrimmingWhitespace] === @"")
return;
[_chatInputField setStringValue:@""];
[_chatInputField setEnabled:NO];
[_chatSendButton setEnabled:NO];
[self appendMessage:prompt isUser:YES];
[self appendMessage:@"Generating response..." isUser:NO];
[_session respondToPrompt:prompt
options:nil
completionHandler:function(finalText, error) {
[_chatInputField setEnabled:YES];
[_chatInputField becomeFirstResponder];
[_chatSendButton setEnabled:YES];
if (error)
[self updateMessage:@"Error: " + [error localizedDescription]];
else
[self updateMessage:finalText];
}];
}
// --- CONFIGURATION POPUP SHEETS ---
- (void)openSettingsSheet:(id)sender
{
if (!_settingsWindow)
{
_settingsWindow = [[CPWindow alloc] initWithContentRect:CGRectMake(0, 0, 420, 260)
styleMask:CPTitledWindowMask | CPClosableWindowMask];
[_settingsWindow setTitle:@"Fallback Settings"];
var sheetContentView = [_settingsWindow contentView];
var sheetBounds = [sheetContentView bounds];
var serviceLabel = [[CPTextField alloc] initWithFrame:CGRectMake(15, 25, 110, 20)];
[serviceLabel setStringValue:@"Service Type:"];
[serviceLabel setFont:[CPFont systemFontOfSize:12.0]];
[serviceLabel setAlignment:CPRightTextAlignment];
[sheetContentView addSubview:serviceLabel];
_servicePopUp = [[CPPopUpButton alloc] initWithFrame:CGRectMake(135, 22, 180, 26) pullsDown:NO];
[_servicePopUp addItemWithTitle:@"Ollama (Local)"];
[[_servicePopUp lastItem] setRepresentedObject:@"ollama"];
[_servicePopUp addItemWithTitle:@"Groq API"];
[[_servicePopUp lastItem] setRepresentedObject:@"groq"];
[_servicePopUp addItemWithTitle:@"Google Gemini"];
[[_servicePopUp lastItem] setRepresentedObject:@"gemini"];
[_servicePopUp addItemWithTitle:@"OpenRouter"];
[[_servicePopUp lastItem] setRepresentedObject:@"openrouter"];
[_servicePopUp setTarget:self];
[_servicePopUp setAction:@selector(serviceTypeDidChange:)];
[sheetContentView addSubview:_servicePopUp];
var endpointLabel = [[CPTextField alloc] initWithFrame:CGRectMake(15, 67, 110, 20)];
[endpointLabel setStringValue:@"Endpoint URL:"];
[endpointLabel setAlignment:CPRightTextAlignment];
[sheetContentView addSubview:endpointLabel];
_endpointField = [[CPTextField alloc] initWithFrame:CGRectMake(135, 62, CGRectGetWidth(sheetBounds) - 155, 27)];
[_endpointField setEditable:YES];
[_endpointField setBezeled:YES];
[sheetContentView addSubview:_endpointField];
var modelLabel = [[CPTextField alloc] initWithFrame:CGRectMake(15, 107, 110, 20)];
[modelLabel setStringValue:@"Model Name:"];
[modelLabel setAlignment:CPRightTextAlignment];
[sheetContentView addSubview:modelLabel];
_modelField = [[CPTextField alloc] initWithFrame:CGRectMake(135, 102, CGRectGetWidth(sheetBounds) - 155, 27)];
[_modelField setEditable:YES];
[_modelField setBezeled:YES];
[sheetContentView addSubview:_modelField];
var apiKeyLabel = [[CPTextField alloc] initWithFrame:CGRectMake(15, 147, 110, 20)];
[apiKeyLabel setStringValue:@"API Key:"];
[apiKeyLabel setAlignment:CPRightTextAlignment];
[sheetContentView addSubview:apiKeyLabel];
_apiKeyField = [[CPTextField alloc] initWithFrame:CGRectMake(135, 142, CGRectGetWidth(sheetBounds) - 155, 27)];
[_apiKeyField setEditable:YES];
[_apiKeyField setBezeled:YES];
[_apiKeyField setSecure:YES];
[sheetContentView addSubview:_apiKeyField];
var btnY = CGRectGetHeight(sheetBounds) - 45;
var cancelBtn = [[CPButton alloc] initWithFrame:CGRectMake(CGRectGetWidth(sheetBounds) - 205, btnY, 90, 26)];
[cancelBtn setTitle:@"Cancel"];
[cancelBtn setTarget:self];
[cancelBtn setAction:@selector(closeSettingsSheet:)];
[sheetContentView addSubview:cancelBtn];
var saveBtn = [[CPButton alloc] initWithFrame:CGRectMake(CGRectGetWidth(sheetBounds) - 105, btnY, 90, 26)];
[saveBtn setTitle:@"Save"];
[saveBtn setTarget:self];
[saveBtn setAction:@selector(saveSettings:)];
[sheetContentView addSubview:saveBtn];
}
var defaults = [CPUserDefaults standardUserDefaults];
var activeService = [defaults objectForKey:@"LLMTestServiceType"] || @"ollama";
if (activeService === @"ollama") [_servicePopUp selectItemAtIndex:0];
else if (activeService === @"groq") [_servicePopUp selectItemAtIndex:1];
else if (activeService === @"gemini") [_servicePopUp selectItemAtIndex:2];
else if (activeService === @"openrouter") [_servicePopUp selectItemAtIndex:3];
[_endpointField setStringValue:[defaults objectForKey:@"LLMTestEndpoint"] || @"http://localhost:11434/api/generate"];
[_modelField setStringValue:[defaults objectForKey:@"LLMTestModel"] || @"gemma4:e4b"];
[_apiKeyField setStringValue:[defaults objectForKey:@"LLMTestAPIKey"] || @""];
[self updateFieldsForService:activeService];
[CPApp beginSheet:_settingsWindow
modalForWindow:_mainWindow
modalDelegate:self
didEndSelector:nil
contextInfo:nil];
}
- (void)updateFieldsForService:(CPString)serviceType
{
if (serviceType === @"ollama") {
[_endpointField setEnabled:YES];
[_apiKeyField setEnabled:NO];
[_apiKeyField setPlaceholderString:@"Not required"];
} else {
[_endpointField setEnabled:NO];
[_endpointField setPlaceholderString:@"Default platform endpoint used"];
[_apiKeyField setEnabled:YES];
[_apiKeyField setPlaceholderString:@"API Token values"];
}
}
- (void)serviceTypeDidChange:(id)sender
{
var newService = [[_servicePopUp selectedItem] representedObject];
[self updateFieldsForService:newService];
}
- (void)closeSettingsSheet:(id)sender
{
[CPApp endSheet:_settingsWindow];
[_settingsWindow orderOut:self];
}
- (void)saveSettings:(id)sender
{
var defaults = [CPUserDefaults standardUserDefaults];
var activeService = [[_servicePopUp selectedItem] representedObject] || @"ollama";
var endpoint = [_endpointField stringValue];
var model = [_modelField stringValue];
var apiKey = [_apiKeyField stringValue];
[defaults setObject:activeService forKey:@"LLMTestServiceType"];
[defaults setObject:endpoint forKey:@"LLMTestEndpoint"];
[defaults setObject:model forKey:@"LLMTestModel"];
[defaults setObject:apiKey forKey:@"LLMTestAPIKey"];
[CPLanguageModelSession setFallbackServiceType:activeService
endpoint:endpoint
model:model
apiKey:apiKey];
[self closeSettingsSheet:sender];
[_statusLabel setStringValue:@"Fallback settings updated."];
}
@end
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CPApplicationDelegateClass</key>
<string>AppController</string>
<key>CPBundleName</key>
<string>CPLanguageModelChatbot</string>
<key>CPPrincipalClass</key>
<string>CPApplication</string>
</dict>
</plist>
@@ -0,0 +1,94 @@
/*
* Jakefile
* CPLevelIndicator
*
* Created by Alexander Ljungberg on May 28, 2011.
* Copyright 2011, WireLoad All rights reserved.
*/
var ENV = require("system").env,
FILE = require("file"),
JAKE = require("jake"),
task = JAKE.task,
FileList = JAKE.FileList,
app = require("cappuccino/jake").app,
configuration = ENV["CONFIG"] || ENV["CONFIGURATION"] || ENV["c"] || "Debug",
OS = require("os");
app ("CPLevelIndicator", function(task)
{
task.setBuildIntermediatesPath(FILE.join("Build", "CPLevelIndicator.build", configuration));
task.setBuildPath(FILE.join("Build", configuration));
task.setProductName("CPLevelIndicator");
task.setIdentifier("com.yourcompany.CPLevelIndicator");
task.setVersion("1.0");
task.setAuthor("WireLoad");
task.setEmail("feedback @nospam@ yourcompany.com");
task.setSummary("CPLevelIndicator");
task.setSources((new FileList("**/*.j")).exclude(FILE.join("Build", "**")));
task.setResources(new FileList("Resources/**"));
task.setIndexFilePath("index.html");
task.setInfoPlistPath("Info.plist");
task.setNib2CibFlags("-R Resources/");
if (configuration === "Debug")
task.setCompilerFlags("-DDEBUG -g");
else
task.setCompilerFlags("-O");
});
task ("default", ["CPLevelIndicator"], function()
{
printResults(configuration);
});
task ("build", ["default"]);
task ("debug", function()
{
ENV["CONFIGURATION"] = "Debug";
JAKE.subjake(["."], "build", ENV);
});
task ("release", function()
{
ENV["CONFIGURATION"] = "Release";
JAKE.subjake(["."], "build", ENV);
});
task ("run", ["debug"], function()
{
OS.system(["open", FILE.join("Build", "Debug", "CPLevelIndicator", "index.html")]);
});
task ("run-release", ["release"], function()
{
OS.system(["open", FILE.join("Build", "Release", "CPLevelIndicator", "index.html")]);
});
task ("deploy", ["release"], function()
{
FILE.mkdirs(FILE.join("Build", "Deployment", "CPLevelIndicator"));
OS.system(["press", "-f", FILE.join("Build", "Release", "CPLevelIndicator"), FILE.join("Build", "Deployment", "CPLevelIndicator")]);
printResults("Deployment")
});
task ("desktop", ["release"], function()
{
FILE.mkdirs(FILE.join("Build", "Desktop", "CPLevelIndicator"));
require("cappuccino/nativehost").buildNativeHost(FILE.join("Build", "Release", "CPLevelIndicator"), FILE.join("Build", "Desktop", "CPLevelIndicator", "CPLevelIndicator.app"));
printResults("Desktop")
});
task ("run-desktop", ["desktop"], function()
{
OS.system([FILE.join("Build", "Desktop", "CPLevelIndicator", "CPLevelIndicator.app", "Contents", "MacOS", "NativeHost"), "-i"]);
});
function printResults(configuration)
{
print("----------------------------");
print(configuration+" app built at path: "+FILE.join("Build", configuration, "CPLevelIndicator"));
print("----------------------------");
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

@@ -0,0 +1,103 @@
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<!--
index-debug.html
CPLevelIndicator
Created by Alexander Ljungberg on May 28, 2011.
Copyright 2011, WireLoad All rights reserved.
-->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7, chrome=1" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="apple-touch-icon" href="Resources/icon.png" />
<link rel="apple-touch-startup-image" href="Resources/default.png" />
<title>CPLevelIndicator</title>
<script type="text/javascript">
OBJJ_MAIN_FILE = "main.j";
OBJJ_INCLUDE_PATHS = ["Frameworks/Debug", "Frameworks", "SomethingElse"];
</script>
<script type="text/javascript" src="Frameworks/Debug/Objective-J/Objective-J.js" charset="UTF-8"></script>
<script type="text/javascript">
objj_msgSend_reset();
// DEBUG OPTIONS:
// Uncomment to enable printing of backtraces on exceptions:
//objj_msgSend_decorate(objj_backtrace_decorator);
// Uncomment to supress exceptions that take place inside a message
//objj_msgSend_decorate(objj_supress_exceptions_decorator)
// Uncomment to enable runtime type checking:
//objj_msgSend_decorate(objj_typecheck_decorator);
// Uncomment (along with both above) to print backtraces on type check errors:
//objj_typecheck_prints_backtrace = true;
// Uncomment to disable the default logger (CPLogConsole if window.console exists, CPLogPopup otherwise):
//CPLogUnregister(CPLogDefault);
// Uncomment to enable a specific logger:
//CPLogRegister(CPLogConsole);
//CPLogRegister(CPLogPopup);
</script>
<style type="text/css">
body{margin:0; padding:0;}
#container {position: absolute; top:50%; left:50%;}
#content {width:800px; text-align:center; margin-left: -400px; height:50px; margin-top:-25px; line-height: 50px;}
#content {font-family: "Helvetica", "Arial", sans-serif; font-size: 18px; color: black; text-shadow: 0px 1px 0px white; }
#loadgraphic {margin-right: 0.2em; margin-bottom:-2px;}
</style>
<!--[if lt IE 7]>
<STYLE type="text/css">
#container { position: relative; top: 50%; }
#content { position: relative;}
</STYLE>
<![endif]-->
</head>
<body style="">
<div id="cappuccino-body">
<div id="loadingcontainer" style="background-color: #eeeeee; overflow:hidden; width:100%; height:100%; position: absolute; top: 0; left: 0;">
<script type="text/javascript">
document.write("<div id='container'><p id='content'>" +
"<img id='loadgraphic' width='16' height='16' src='Resources/spinner.gif' /> " +
"Loading CPLevelIndicator...</p></div>");
</script>
<noscript>
<div id="container">
<div style="width: 440px; padding: 10px 25px 20px 25px; font-family: sans-serif; background-color: #ffffff; position: relative; left: -245px; top: -120px; text-align: center; -moz-border-radius: 20px; -webkit-border-radius: 20px; color: #555555">
<p style="line-height: 1.4em;">JavaScript is required for this site to work correctly but is either disabled or not supported by your browser.</p>
<p style="font-size:120%; padding:10px;"><a href="http://cappuccino-project.org/noscript">Show me how to enable JavaScript</a></p>
<p style="font-size:80%;">You may want to upgrade to a newer browser while you're at it:</p>
<ul style="margin:0;padding:0; text-align: center; font-size:80%;" >
<li style="display: inline;"><a href="http://www.apple.com/safari/download/">Safari</a></li>
<li style="display: inline;"><a href="http://www.mozilla.com/en-US/firefox/">Firefox</a></li>
<li style="display: inline;"><a href="http://www.google.com/chrome/">Chrome</a></li>
<li style="display: inline;"><a href="http://www.opera.com/download/">Opera</a></li>
<li style="display: inline;"><a href="http://www.microsoft.com/windows/downloads/ie/getitnow.mspx">Internet Explorer</a></li>
</ul>
</div>
</div>
</noscript>
</div>
</div>
</body>
</html>
@@ -0,0 +1,166 @@
<!DOCTYPE html>
<html lang="en">
<!--
index.html
__project.name__
Created by __user.name__ on __project.date__.
Copyright __project.year__, __organization.name__ All rights reserved.
-->
<head>
<meta charset="utf-8">
<!--[if lte IE 8]>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7, chrome=1">
<![endif]-->
<!--[if gte IE 9]>
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
<![endif]-->
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="apple-touch-icon" href="Resources/icon.png">
<link rel="apple-touch-startup-image" href="Resources/default.png">
<title>__project.name__</title>
<!-- Custom javascript goes here -->
<!-- End custom javascript -->
<script type="text/javascript">
OBJJ_MAIN_FILE = "main.j";
// The below will tell the compiler to not generate debug symbols but will generate type signatures and inline objj_msgSend functions.
// This will affect only Objective-J code that is compiled when loading the application. It will not affect precompiled
// code like the Cappuccino frameworks.
// Uncomment or comment on the line below to change the flags
OBJJ_COMPILER_FLAGS = ["IncludeDebugSymbols", "IncludeTypeSignatures", "SourceMap", "InlineMsgSend"];
var progressBar = null;
OBJJ_PROGRESS_CALLBACK = function(percent, appSize, path)
{
percent = percent * 100;
if (!progressBar)
progressBar = document.getElementById("progress-bar");
if (progressBar)
progressBar.style.width = Math.min(percent, 100) + "%";
}
var loadingHTML =
'<div id="loading">' +
' <div id="loading-text">Loading...</div>' +
' <div id="progress-indicator">' +
' <span id="progress-bar" style="width:0%"></span>' +
' </div>' +
'</div>';
</script>
<script type="text/javascript" src="Frameworks/Objective-J/Objective-J.js" charset="UTF-8"></script>
<style type="text/css">
html, body, h1, p {
margin: 0;
padding: 0;
}
/* We need a body wrapper because Cappuccino is unhappy if we change the body element */
#cappuccino-body {
/* Position it absolutely so it will fill the height without content */
position: absolute;
top: 0;
bottom: 0;
width: 100%;
/* Put it at the bottom of the stack so it doesn't interfere with UI */
z-index: 0;
}
#cappuccino-body .container {
display: table;
margin: 0 auto;
height: 100%;
}
#cappuccino-body .content {
display: table-cell;
height: 100%;
vertical-align: top;
}
#loading {
position: relative;
top: 35%;
}
#loading-text {
height: 1.5em;
color: #555;
font: normal bold 36px/36px Arial, sans-serif;
}
#progress-indicator {
padding: 0px;
height: 16px;
border: 5px solid #555;
border-radius: 18px;
background-color: white;
}
#progress-bar {
position: relative;
top: -1px;
left: -1px;
display: block;
height: 18px;
/* Compensate for moving the bar left 1px to overlap the indicator border */
border-right: 1px solid #555;
background-color: #555;
}
#noscript {
position: relative;
top: 35%;
padding: 1em 1.5em;
border: 5px solid #555;
border-radius: 16px;
background-color: white;
color: #555;
text-align: center;
font: bold 24px Arial, sans-serif;
}
#noscript a {
color: #98c0ff;
text-decoration: none;
}
</style>
</head>
<body>
<div id="cappuccino-body">
<div class="container">
<div class="content">
<script type="text/javascript">
document.write(loadingHTML);
</script>
</div>
</div>
<noscript style="position:absolute; top:0; left:0; width:100%; height:100%">
<div class="container">
<div class="content">
<div id="noscript">
<p style="font-size:120%; margin-bottom:.75em">JavaScript is required for this application.</p>
<p><a href="http://www.enable-javascript.com" target="_blank">Enable JavaScript</a></p>
</div>
</div>
</div>
</noscript>
</div>
</body>
</html>
@@ -0,0 +1,18 @@
/*
* AppController.j
* CPLevelIndicator
*
* Created by Alexander Ljungberg on May 28, 2011.
* Copyright 2011, WireLoad All rights reserved.
*/
@import <Foundation/Foundation.j>
@import <AppKit/AppKit.j>
@import "AppController.j"
function main(args, namedArgs)
{
CPApplicationMain(args, namedArgs);
}