diff --git a/addons/CountryListBox.py b/addons/CountryListBox.py index da32d4e6a..5d429e38e 100644 --- a/addons/CountryListBox.py +++ b/addons/CountryListBox.py @@ -255,7 +255,7 @@ class CountryListBox(ListBox): def __init__(self): ListBox.__init__(self) self.addCountries() - + def addCountries(self): for countryItem in self.country_list: self.addItem(countryItem[0], countryItem[1]) diff --git a/addons/DeferredHandler.py b/addons/DeferredHandler.py index d8330a022..a6b54b426 100644 --- a/addons/DeferredHandler.py +++ b/addons/DeferredHandler.py @@ -4,17 +4,17 @@ @contact: tobi-weber@gmx.de """ -from pyjamas.Timer import Timer +from pyjamas.Timer import Timer global deferredHandlers deferredHandlers = [] global timerIsActive -timerIsActive = False - +timerIsActive = False + def add(handler, arguments=[]): deferredHandlers.append([handler, arguments]) maybeSetDeferredHandlerTimer() - + def flushDeferredHandlers(): for i in range(len(deferredHandlers)): current = deferredHandlers[0] @@ -23,17 +23,17 @@ def flushDeferredHandlers(): handler = current[0] args = current[1] handler(*args) - + def maybeSetDeferredHandlerTimer(): global timerIsActive - + if (not timerIsActive) and (not len(deferredHandlers)==0): Timer(1, onTimer) timerIsActive = True - + def onTimer(t): global timerIsActive - + flushDeferredHandlers() timerIsActive = False - maybeSetDeferredHandlerTimer() \ No newline at end of file + maybeSetDeferredHandlerTimer() diff --git a/addons/FlowPlayer.py b/addons/FlowPlayer.py index 862f42903..0940e848f 100644 --- a/addons/FlowPlayer.py +++ b/addons/FlowPlayer.py @@ -30,14 +30,14 @@ def fireEvent(self, *args): if args[i] != None: arguments.append(args[i]) wnd().players[args[0]].fireEvent(movieName, eventName, arguments) - + def setInstanceGlobal(movieName, instance): wnd().players[movieName] = instance - + wnd().players = {} wnd().flowplayer = PlayerEventCatcher() - - + + # Counter for Flash-movies global movieCount movieCount = 0 @@ -48,9 +48,9 @@ def getMovieCount(): class Player(FlashPanel): """ - Embedding and api handling of Flowplayer + Embedding and api handling of Flowplayer """ - + clip_events = ['onBegin', 'onBeforeBegin', 'onFinish', 'onBeforeFinish', 'onLastSecond', 'onMetaData', 'onPause', 'onBeforePause', 'onResume', 'onBeforeResume', 'onSeek', 'onBeforeSeek', 'onStart', 'onStop', 'onBeforeStop', 'onUpdate', @@ -63,7 +63,7 @@ def __init__(self, url, config=None): """ FlashPanel.__init__(self) global movieCount - + self.api = None self.playlist = [] self.plugins = {} @@ -72,12 +72,12 @@ def __init__(self, url, config=None): self.common_clip = None self.playlist = None self.curClip = None - + self.playerId = 'flowplayer'+str(movieCount) self.movieName = self.playerId+'_api' movieCount+=1 setInstanceGlobal(self.movieName, self) - + #self.setObjectClass('flowplayer') self.setObjectID(self.movieName) self.setID(self.playerId) @@ -101,17 +101,17 @@ def __init__(self, url, config=None): plugin.setPlayer(self) self.plugins['screen'] = plugin self.flashvars = self.__createFlashVars(config) - + def loadApi(self): """ Load the Flowplayer api """ self.api = self.getMovieElement() - + def __getObjectAsString(self, obj): """ @param obj: Object - + @return: String """ obj_string = '{' @@ -132,21 +132,21 @@ def __getObjectAsString(self, obj): i+=1 obj_string += '}' return obj_string - + def __createFlashVars(self, config): """ @param config: Configuration Object - + @return: String - + Build Flashparams from Configuration """ # Begin Config config_string = 'config={' - + # PlayerId config_string += '"playerId":"%s",' % self.movieName - + # Plugins if config.plugins: config_string += '"plugins":{' @@ -163,8 +163,8 @@ def __createFlashVars(self, config): if not config.controls and not controls: config_string += ',"controls":null' config_string += '},' - - + + # Common Clip config_string += '"clip":' if config.common_clip: @@ -172,7 +172,7 @@ def __createFlashVars(self, config): config_string += ',' else: config_string += '{},' - + # Playlist config_string += '"playlist":[' if config.playlist: @@ -185,11 +185,11 @@ def __createFlashVars(self, config): else: config_string += '{}' config_string += ']' - + # Debug if config.debug: config_string += ',"debug":true,"log":{"level":"%s","filter":"%s"}' % (config.logLevel, config.logFilter) - + # End Config config_string += '}' config_string = config_string.replace('%', 'pct') @@ -200,11 +200,11 @@ def __createFlashVars(self, config): config_string = config_string.replace('\'', '\\\'') #log.debug(config_string) return config_string - + def fireEvent(self, movieName, eventName, arguments): """ @param args: Arguments given by Flowplayer - + Fire event """ #log.debug('FireEvent: %s/%s/%s' % (movieName, eventName, str(arguments))) @@ -257,23 +257,23 @@ def fireEvent(self, movieName, eventName, arguments): if hasattr(listener, eventName): eventMethod = getattr(listener, eventName) DeferredHandler.add(eventMethod, arguments) - + def addListener(self, listener): """ @param listener: Object - + Add a listener """ self.listeners.append(listener) - + def removeListener(self, listener): """ @param listener: Object - - Remove a listener + + Remove a listener """ self.listeners.remove(listener) - + def isLoaded(self): """ @return: Boolean, if the player is loaded @@ -282,18 +282,18 @@ def isLoaded(self): return True else: return False - + # Flash ExternalInterface calls - + def addClip(self, clip, index=None): """ @param clip: Clip Object @param index: specifies the position where clip is added in the playlist - + Add's a clip to the playlist. If the clip object contains a position property then the clip is added to an existing clip as an instream clip. The player's playlist is extended with the new clip and the onClipAdd event is fired. - All common clip properties and event listeners are preserved. + All common clip properties and event listeners are preserved. """ if self.isLoaded(): if index: @@ -302,25 +302,25 @@ def addClip(self, clip, index=None): else: self.playlist.append(clip) self.callFlash('fp_addClip', [clip.getProperties()]) - + def setClip(self, clip): """ @param clip: Clip Object - + Replaces the current playlist with a playlist consisting of a single clip. All common clip properties and events are preserved. - After this an onPlaylistReplace event fires. + After this an onPlaylistReplace event fires. """ if self.isLoaded(): self.setPlaylist([clip]) - + def getClip(self, index=None): """ - @param index: Position in the playlist - + @param index: Position in the playlist + @return: clip object from the playlist specified by index. - - For example getClip(0) returns the first clip from the playlist. + + For example getClip(0) returns the first clip from the playlist. If called without an index the current clip will be returned. """ if self.isLoaded(): @@ -331,29 +331,29 @@ def getClip(self, index=None): return self.playlist[index] else: return None - + def getCurrentClip(self): # TODO return None - + def close(self): """ - Closes all connections between the player and the server. This method + Closes all connections between the player and the server. This method is usually automatically called for you but in some cases you may want to do this yourself. """ if self.isLoaded(): self.callFlash('fp_close', []) - + def getTime(self): """ - @return: current time, in seconds, of the current clip. + @return: current time, in seconds, of the current clip. """ if self.isLoaded(): return self.callFlash('fp_getTime', []) else: return None - + def getVersion(self): """ @return: Flowplayer version @@ -362,11 +362,11 @@ def getVersion(self): return self.callFlash('fp_getVersion', []) else: return None - + def getPlugin(self, name): """ @param name: Plugins name - + @return: plugin with the given name """ if self.plugins.has_key(name): @@ -374,11 +374,11 @@ def getPlugin(self, name): return plugin else: return None - + def loadPlugin(self, plugin): """ @param plugin: Plugin object - + Loads a plugin in the player. """ if self.isLoaded(): @@ -386,7 +386,7 @@ def loadPlugin(self, plugin): plugin.setPlayer(self) self.plugins[plugin.name] = plugin self.callFlash('fp_loadPlugin', [plugin.name, plugin.url, properties]) - + def getState(self): """ @return: state of the player. Possible values are: @@ -402,7 +402,7 @@ def getState(self): return self.callFlash('fp_getState', []) else: return -1 - + def getVolume(self): """ @return: player's current volume setting as an integer between 0-100. @@ -412,45 +412,45 @@ def getVolume(self): return self.callFlash('fp_getVolume', []) else: return None - + def setVolume(self, volume): """ @param volume: Integer between 0-100 - - Sets the volume. 0 is totally muted. + + Sets the volume. 0 is totally muted. """ if self.isLoaded(): self.callFlash('fp_setVolume', [volume]) - + def isFullscreen(self): """ - @return: True if the player is in full screen mode and False otherwise. + @return: True if the player is in full screen mode and False otherwise. """ if self.isLoaded(): return self.callFlash('fp_isFullscreen', []) else: return None - + def toggleFullscreen(self): """ - Toggles the state between fullscreen and normal mode. - + Toggles the state between fullscreen and normal mode. + @return: True if the player is in full screen mode and False otherwise. """ if self.isLoaded(): return self.callFlash('fp_toggleFullscreen', []) else: return None - + def isPaused(self): """ - @return: True if the player is paused and False otherwise. + @return: True if the player is paused and False otherwise. """ if self.isLoaded(): return self.callFlash('fp_isPaused', []) else: return None - + def isPlaying(self): """ @return: True if the player is playing and False otherwise. @@ -459,84 +459,84 @@ def isPlaying(self): return self.callFlash('fp_isPlaying', []) else: return None - + def mute(self): """ Mutes the player. The difference between this and setVolume(0) is that the - original volume level is remembered and resumed when unmute() is called. + original volume level is remembered and resumed when unmute() is called. """ if self.isLoaded(): self.callFlash('fp_mute', []) - + def unmute(self): """ - Resumes the volume level that was set before the player was muted. + Resumes the volume level that was set before the player was muted. """ if self.isLoaded(): self.callFlash('fp_unmute', []) - + def pause(self): """ Pauses the currently playing clip. """ if self.isLoaded(): self.callFlash('fp_pause', []) - + def play(self): """ - starts playback of the current clip. + starts playback of the current clip. """ if self.isLoaded(): self.callFlash('fp_play', []) - + def playIndex(self, index): """ @param index: the zero-based index of the clip in the Player's playlist array. - + Starts playback of the clip specified by index. """ if self.isLoaded(): self.callFlash('fp_play', [index]) - + def playClip(self, clip): """ - @param clip: Clip object - + @param clip: Clip object + Plays the clip. The player's playlist is replaced with a new playlist consisting of this single clip and the onPlaylistReplace event is fired. - All common clip properties and event listeners are preserved. + All common clip properties and event listeners are preserved. """ if self.isLoaded(): self.playlist = [clip] self.callFlash('fp_play', [clip.getProperties()]) - + def playClips(self, clips): """ @param clips: List of clips - + Play the playlist specified by a List of clips. The player's playlist is replaced with a new playlist consisting of these clips and the onPlaylistReplace event is fired. All common clip properties and event - listeners are preserved. + listeners are preserved. """ if self.isLoaded(): self.playlist = clips self.callFlash('fp_play', [self.playlist]) - + def toggle(self): """ Toggles the state between play and pause. """ if self.isLoaded(): self.callFlash('fp_toggle', []) - + def stop(self): """ Stops the current clip. """ if self.isLoaded(): self.callFlash('fp_stop', []) - + def reset(self, pluginNames=None, speed=None): """ If you have moved your screen or controlbar, this call moves them back to @@ -551,78 +551,78 @@ def reset(self, pluginNames=None, speed=None): self.callFlash('fp_reset', [pluginNames]) else: # Reset Controls and Screens self.callFlash('fp_reset', []) - + def resume(self): """ Resumes the currently paused clip. """ if self.isLoaded(): self.callFlash('fp_resume', []) - + def seek(self, seconds): """ Seeks to the specified time of the current clip, in seconds. If using - default URL-based streaming provider then the buffer must have loaded + default URL-based streaming provider then the buffer must have loaded to the point of seeking. When using streaming server this is not required. """ if self.isLoaded(): self.callFlash('fp_seek', [seconds]) - + def startBuffering(self): """ - Starts downloading video data from the server. + Starts downloading video data from the server. """ if self.isLoaded(): self.callFlash('fp_startBuffering', []) - + def stopBuffering(self): """ - Stops downloading video data from the server. + Stops downloading video data from the server. """ if self.isLoaded(): self.callFlash('fp_stopBuffering', []) - + def getPlaylist(self): """ - Returns the playlist of the player as a list of Clip objects. + Returns the playlist of the player as a list of Clip objects. """ return self.playlist - + def setPlaylist(self, clips): """ @param clips: List of clips - + Replaces the current playlist with a new one. The playlist is given as a list of clips. All common clip properties are preserved. - After this an onPlaylistReplace event fires. + After this an onPlaylistReplace event fires. """ if self.isLoaded(): self.playlist = clips self.callFlash('fp_setPlaylist', [self.playlist]) - + def updateClip(self, clip): """ @param clip: clip object - + Updates a clip, if the clip properties are changed """ if self.isLoaded(): index = self.playlist.index(clip) self.callFlash('fp_updateClip', [clip.getProperties(), index]) - + def getScreen(self): """ @return: the screen plugin """ return self.getPlugin('screen') - + def getControls(self): """ @return: the controls plugin """ return self.getPlugin('controls') - - + + class Configuration: """ Defines the Startup Configuration of FlowPlayer @@ -632,7 +632,7 @@ class Configuration: @var logFilter: String """ def __init__(self): - self.controls = True + self.controls = True """Boolean, if controls are enabled. Default: True""" self.debug = False """Boolean, for debugging""" @@ -640,32 +640,32 @@ def __init__(self): """ Loglevel """ self.logFilter = '*' """ Logfilter """ - + self.plugins = [] self.common_clip = Clip() self.playlist = [] - + def addPlugin(self, plugin): """ @param plugin: Plugin object """ self.plugins.append(plugin) - + def setCommonClip(self, clip): """ @param clip: Clip object """ self.common_clip = clip - + def setPlaylist(self, playlist): """ @param playlist: List with Clips """ self.playlist = playlist - + def disableControls(self): self.controls = False - + class Clip: """ Clip for the player @@ -698,66 +698,66 @@ class Clip: 'urlResolver' # String ] """ Possible Attributes for a Clip; Can be added with setAttr-Method """ - + def __init__(self, url=None): self._player = None self.listeners = [] if url: setattr(self, 'url', url) - + def setAttr(self, attr, value): """ @param attr: Properties name @param value: Properties value - + Sets a Property to this Object """ if attr in self.attrs: setattr(self, attr, value) self.update() - + def setPlayer(self, player): """ @param player: Player Instance """ self._player = player - + def getPlayer(self): """ @return: The player instance """ return self._player - + def update(self): """ Updates this clip instance, if it is changed on runtime """ if self._player: self._player.updateClip(self) - + def addListener(self, listener): """ @param listener: Object - + Add a listener """ self.listeners.append(listener) - + def removeListener(self, listener): """ @param listener: Object - + Remove a listener """ self.listeners.remove(listener) - + def fireEvent(self, eventName, arguments): for listener in self.listeners: if hasattr(listener, eventName): eventMethod = getattr(listener, eventName) arguments.insert(0, self) DeferredHandler.add(eventMethod, arguments) - + def getProperties(self): """ @return: Dictonary with Properties @@ -767,12 +767,12 @@ def getProperties(self): if hasattr(self, attr): properties[attr] = getattr(self, attr) return properties - + class Plugin: """ Base class for plugins """ - + attrs = ['url', 'bottom', 'height', @@ -792,7 +792,7 @@ class Plugin: 'backgroundGradient', 'backgroundImage'] """ Possible Attributes for a Plugin; Can be added with setAttr-Method """ - + def __init__(self, url=None, name=None): if url: self.url = url @@ -801,39 +801,39 @@ def __init__(self, url=None, name=None): self._player = None self.listeners = [] self.loaded = False - + def setAttr(self, attr, value): """ @param attr: Properties name @param value: Properties value - + Sets a Property to this Object """ if attr in self.attrs: setattr(self, attr, value) - + def setPlayer(self, player): """ @param player: Player Instance """ self._player = player - + def isLoaded(self): """ Returns a Boolean, if the plugin is loaded """ return self.loaded - + def animate(self, properties, speed=500): """ - @param properties: Dictonary; the plugin's placement, + @param properties: Dictonary; the plugin's placement, size and opacity properties that you want to animate - + @param speed: Integer; specifies the duration of the animation, in milliseconds. - - animate() lets you change a plugin's position, size and opacity in an animated way. + + animate() lets you change a plugin's position, size and opacity in an animated way. This can give very cool effects on your web page. - You can also do relative animations by prepending a "+=" or "-=" to the property + You can also do relative animations by prepending a "+=" or "-=" to the property value to animate relative to the property's current value. plugin.animate({width:'80%'}) """ @@ -841,103 +841,103 @@ def animate(self, properties, speed=500): if self.name: callback = 'onAnimate' self._player.callFlash('fp_animate', [self.name, properties, speed, callback]) - + def css(self, properties): """ @param properties: Dictonary - + Changes the plugin's style and other properties immediately without animation. - Change controlbar background color + Change controlbar background color controls.css({backgroundColor:'#cccccc'}) """ if self.loaded and self._player: if self.name: self._player.callFlash('fp_css', [self.name, properties]) - + def fadeIn(self, speed=500): """ @param speed: Integer; specifies the duration of the animation, in milliseconds. - + Makes the plugin visible in an animated way by adjusting its opacity - from the initial opacity to 100%. In typical scenarios the initial - opacity is 0. This call will also set the plugin's display property + from the initial opacity to 100%. In typical scenarios the initial + opacity is 0. This call will also set the plugin's display property to "block", making it visible if it was hidden. """ if self.loaded and self._player: callback = 'onAnimate' if self.name: self._player.callFlash('fp_fadeIn', [self.name, speed, callback]) - + def fadeOut(self, speed=500): """ @param speed: Integer; specifies the duration of the animation, in milliseconds. - - Hides the plugin in an animated manner by adjusting its opacity from - the initial opacity to 0%. This call will also set the plugin's display + + Hides the plugin in an animated manner by adjusting its opacity from + the initial opacity to 0%. This call will also set the plugin's display property to "none", removing it completely from the canvas. """ if self.loaded and self._player: callback = 'onAnimate' if self.name: self._player.callFlash('fp_fadeOut', [self.name, speed, callback]) - + def fadeTo(self, opacity=100, speed=500): """ @param opacity: specifies the end opacity of the animation (0 - 100). - + @param speed: Integer; specifies the duration of the animation, in milliseconds. - - Makes the plugin hidden in an animated manner by adjusting its opacity + + Makes the plugin hidden in an animated manner by adjusting its opacity from the initial opacity to the given opacity. """ if self.loaded and self._player: callback = 'onAnimate' if self.name: self._player.callFlash('fp_fadeTo', [self.name, opacity, speed, callback]) - + def hide(self): """ - Immediately hides the plugin and removes it from the canvas. - This is the same as setting the display property to "none". - This does not affect the plugin's opacity setting. + Immediately hides the plugin and removes it from the canvas. + This is the same as setting the display property to "none". + This does not affect the plugin's opacity setting. """ if self.loaded and self._player: if self.name: self._player.callFlash('fp_hidePlugin', [self.name]) - + def show(self): """ - Makes the plugin immediately visible. This does not affect the plugin's - opacity setting. This is the same as setting the display property to "block". + Makes the plugin immediately visible. This does not affect the plugin's + opacity setting. This is the same as setting the display property to "block". """ if self.loaded and self._player: if self.name: self._player.callFlash('fp_showPlugin', [self.name]) - + def toggle(self): """ - Toggles between the hidden and visible state. + Toggles between the hidden and visible state. """ if self.loaded and self._player: if self.name: self._player.callFlash('fp_togglePlugin', [self.name]) - + def addListener(self, listener): """ @param listener: object - + Add a listener object """ self.listeners.append(listener) - + def removeListener(self, listener): """ @param listener: object - + Remove a listener object """ self.listeners.remove(listener) - + def fireEvent(self, eventName): """ @param eventName: Name of the event @@ -947,7 +947,7 @@ def fireEvent(self, eventName): if hasattr(listener, eventName): eventMethod = getattr(listener, eventName) DeferredHandler.add(eventMethod, [self]) - + def getProperties(self): """ @return: Dictonary with properties of this instance @@ -958,16 +958,16 @@ def getProperties(self): if not attr == 'url': properties[attr] = getattr(self, attr) return properties - - + + class ScreenPlugin(Plugin): """ The main screen """ - + def __init__(self): Plugin.__init__(self, name='screen') - + class ContentPlugin(Plugin): @@ -977,16 +977,16 @@ class ContentPlugin(Plugin): content_attrs = ['html', 'textDecoration', 'stylesheet', - 'style', + 'style', 'closeButton', 'closeImage'] """ Additional Attributes for a ContentPlugin; Can be added with setAttr-Method """ - + def __init__(self, url=None, name=None): Plugin.__init__(self, url, name) self.attrs += self.content_attrs """ Possible ContentPlugin Attributes """ - + def setHtml(self, html): """ @param html: Set the plugin's HTML content to the given string. @@ -994,7 +994,7 @@ def setHtml(self, html): if self.loaded: if self.name: self._player.callFlash('fp_invoke', [self.name, 'setHtml', html]) - + def append(self, html): """ @param html: append more HTML content to the end of the existing HTML. @@ -1002,7 +1002,7 @@ def append(self, html): if self.loaded: if self.name: self._player.callFlash('fp_invoke', [self.name, 'append', html]) - + def getHtml(self): """ @return: the current HTML content. @@ -1012,13 +1012,13 @@ def getHtml(self): if self.name: html = self._player.callFlash('fp_invoke', [self.name, 'getHtml']) return html - - + + class ControlsPlugin(Plugin): """ The controlbar for the player """ - + control_attrs = ['timeColor', 'durationColor', 'progressColor', @@ -1048,13 +1048,13 @@ class ControlsPlugin(Plugin): 'fullscreen', 'scrubber'] """ Additional Attributes for a ControlsPlugin; Can be added with setAttr-Method """ - + def __init__(self, url=None, name=None): name = 'controls' Plugin.__init__(self, url, name) self.attrs += self.control_attrs """ Possible ControlsPlugin Attributes """ - + def getDefaultProperties(self): properties = {'autoHide': 'fullscreen', # never, always, fullscreen 'hideDelay': 4000, @@ -1067,48 +1067,48 @@ def getDefaultProperties(self): 'fullscreen': True, 'scrubber': True } - + def enable(self, properties): """ @param properties: Dictionary - + Enables and/or disables the controlbar widgets. Disabled widgets are greyed out. - For example, this can be useful when you want to force the user to watch a - video in the case of an advertisement. A value of all can be used to enable/disable - all widgets at the same time. For example, enable({all: False}) will disable all widgets. + For example, this can be useful when you want to force the user to watch a + video in the case of an advertisement. A value of all can be used to enable/disable + all widgets at the same time. For example, enable({all: False}) will disable all widgets. Example: properties = {play: False} """ if self.loaded: if self.name: self._player.callFlash('fp_invoke', [self.name, 'enable', properties]) - + def widgets(self, properties): """ @param properties: Dictionary - - Shows/hides the controlbar widgets. - all can be used to enable/disable all widgets at the same time, - for example, widgets({all: False}). + + Shows/hides the controlbar widgets. + all can be used to enable/disable all widgets at the same time, + for example, widgets({all: False}). Example: properties = {scrubber: False} """ if self.loaded: if self.name: self._player.callFlash('fp_invoke', [self.name, 'widgets', properties]) - + def tooltips(self, properties): """ @param properties: Dictionary - - Enables/disables tooltips. Use buttons:true or buttons:false to enable or disable all - buttons at the same time, respectively. Specifying the value null disables the tooltip. + + Enables/disables tooltips. Use buttons:true or buttons:false to enable or disable all + buttons at the same time, respectively. Specifying the value null disables the tooltip. If you want to enable the buttons remember to add the buttons: True property as one parameter. Example: properties = {buttons: True, play: 'Go'} """ if self.loaded: if self.name: self._player.callFlash('fp_invoke', [self.name, 'tooltips', properties]) - - + + class PseudostreamingPlugin(Plugin): """ Webserver video streaming plugin @@ -1121,7 +1121,7 @@ def __init__(self, url=None, name=None): if not url: url = 'flowplayer.pseudostreaming.swf' Plugin.__init__(self, url, name) - + class AudioPlugin(Plugin): """ Audio plugin @@ -1133,114 +1133,113 @@ def __init__(self, url=None): if not url: url = 'flowplayer.audio.swf' Plugin.__init__(self, url, name) - - + + class PlayerInterface: """ Player Events Interface """ def onBeforeClick(self): pass - + def onLoaded(self): pass def onBeforeLoaded(self): pass - + def onUnload(self): pass - + def onBeforeUnload(self): pass - + def onKeypress(self, keycode): pass - + def onBeforeKeypress(self, keycode): pass - + def onVolume(self, volume): pass - + def onBeforeVolume(self, volume): pass - + def onMute(self): pass - + def onBeforeMute(self): pass - + def onUnmute(self): pass - + def onBeforeUnmute(self): pass - + def onFullscreen(self): pass - + def onBeforeFullscreen(self): pass - + def onFullscreenExit(self): pass - + def onClipAdd(self, clip, index): pass - + def onPlaylistReplace(self, clips): pass - + def onError(self, code, message): pass - + def onMouseOver(self): pass - + def onMouseOut(self): pass - + def onFirstPlaylistItem(self): pass - + def onLastPlaylistItem(self): pass - - + + class ClipInterface: """ Clip Events Interface """ def onBegin(self, clip): pass - + def onBeforeBegin(self, clip): pass - + def onFinish(self, clip): pass - + def onBeforeFinish(self, clip): pass - + def onLastSecond(self, clip): pass - + def onMetaData(self, clip): pass - + def onPause(self, clip): pass - + def onBeforePause(self, clip): pass - + def onResume(self, clip): pass - + def onBeforeResume(self, clip): pass - + def onSeek(self, clip, seconds): pass - + def onBeforeSeek(self, clip, seconds): pass - + def onStart(self, clip): pass - + def onStop(self, clip): pass - + def onBeforeStop(self, clip): pass - + def onUpdate(self, clip): pass - - def onBufferEmpty(self, clip): pass - + + def onBufferEmpty(self, clip): pass + def onBufferFull(self, clip): pass - + def onBufferStop(self, clip): pass - + def onNetStreamEvent(self, clip): pass - - + + class PluginInterface: """ Plugin Events Interface """ - + def onMouseOverPlugin(self, plugin): pass - + def onMouseOutPlugin(self, plugin): pass - + def onAnimatePlugin(self, plugin): pass - + def onClickPlugin(self, plugin): pass - \ No newline at end of file diff --git a/addons/RichTextEditor.py b/addons/RichTextEditor.py index 40a94ba57..e4c3ac4d4 100644 --- a/addons/RichTextEditor.py +++ b/addons/RichTextEditor.py @@ -32,7 +32,7 @@ def createFCK(name): class RichTextEditor(Widget): - def __init__(self, initialValue="", target="", method="POST", + def __init__(self, initialValue="", target="", method="POST", basePath=None, **kwargs): self.id = "rte" + str(hash(self)) diff --git a/addons/SWFUpload.py b/addons/SWFUpload.py index add8f57e9..a5b24290c 100644 --- a/addons/SWFUpload.py +++ b/addons/SWFUpload.py @@ -16,24 +16,24 @@ class SWFUploadInstances: - + def addInstance(self, movieName, instance): setattr(self, movieName, instance) - + class SWFUploadEventCatcher: - + def __init__(self): self.instances = SWFUploadInstances() - + def addInstance(self, movieName, instance): self.instances.addInstance(movieName, instance) - -# Global variable called by Flash External Interface + +# Global variable called by Flash External Interface wnd().SWFUpload = SWFUploadEventCatcher() - + def setInstanceGlobal(movieName, instance): wnd().SWFUpload.addInstance(movieName, instance) - + # Counter for Flash-movies global movieCount movieCount = 0 @@ -46,7 +46,7 @@ class SWFUpload(FlashPanel): """ Embedding and api handling of SWFUpload """ - + QUEUE_ERROR = { 'QUEUE_LIMIT_EXCEEDED' : -100, 'FILE_EXCEEDS_SIZE_LIMIT' : -110, @@ -86,11 +86,11 @@ class SWFUpload(FlashPanel): 'TRANSPARENT' : "transparent", 'OPAQUE' : "opaque" } - + def __init__(self): FlashPanel.__init__(self) global movieCount - + self.settings = None self.eventQueue = [] self.setObjectClass('swfupload') @@ -100,13 +100,13 @@ def __init__(self): self.setWmode('window') self.setMenu(False) setInstanceGlobal(self.movieName, self) - + def getSettings(self): """ @return: the settings instance """ return self.settings - + def setSettings(self, settings): """ @param settings: An instance of Settings @@ -116,11 +116,11 @@ def setSettings(self, settings): self.setObjectWidth(self.settings.getButtonWidth()) self.setObjectHeight(self.settings.getButtonHeight()) self.flashvars = self.__createFlashVars() - + def __createFlashVars(self): httpSuccessString = ','.join(self.settings.http_success) paramString = self.__buildParamString() - vars = [ + vars = [ "movieName=", quote(self.object_id), "&uploadURL=", quote(self.settings.upload_url), "&useQueryString=", quote(self.settings.use_query_string), @@ -147,21 +147,21 @@ def __createFlashVars(self): "&buttonCursor=", quote(self.settings.button_cursor) ] return ''.join(vars) - + def __buildParamString(self): postParams = self.settings.post_params paramStringPairs = [] for k,v in postParams: paramStringPairs.append(quote(k) + "=" + quote(v)) return '&'.join(paramStringPairs) - + def callFlash(self, functionName, arguments=[]): """ @param functionName: Methodname of ExternalInterface @param arguments: List with arguments of ExternalInterfaces method - + @return: the return value of ExternalInterfaces method. - + Extended method from FlashPanel. """ returnValue = FlashPanel.callFlash(self, functionName, arguments) @@ -171,11 +171,11 @@ def callFlash(self, functionName, arguments=[]): except: pass return returnValue - + def startUpload(self, file_id=None): """ @param file_id: The file id - + startUpload causes the file specified by the file_id parameter to start the upload process. If the file_id parameter is omitted then the first file in the queue is uploaded. @@ -184,102 +184,102 @@ def startUpload(self, file_id=None): self.callFlash('StartUpload', [file_id]) else: self.callFlash('StartUpload') - + def cancelUpload(self, file_id, triggerErrorEvent=True): """ @param triggerErrorEvent: Boolean, Default: True - + cancelUpload cancels the file specified by the file_id parameter. The file is then removed from the queue. """ self.callFlash('CancelUpload', [file_id, triggerErrorEvent]) - + def stopUpload(self): """ stopUpload stops and re-queues the file currently being uploaded. """ self.callFlash('StopUpload') - + def getFileByIndex(self, index): """ @param index: The file index in the queue - + @return: retrieve a File Object from the queue by the file index. """ return self.callFlash('GetFileByIndex', [index]) - + def getFile(self, file_id): """ @param file_id: The file id - + @return: retrieve a File Object from the queue by the file id """ return self.callFlash('GetFile', [file_id]) - + def addFileParam(self, file_id, name, value): """ @param file_id: The file id @param name: Name of the parameter @param value: Value of the parameter - + The addFileParam function adds a name/value pair that will be sent in the POST with the file specified by the file_id parameter. - The name/value pair will only be sent with the file it is added to. + The name/value pair will only be sent with the file it is added to. """ self.callFlash('AddFileParam', [file_id, name, value]) - + def removeFileParam(self, file_id, name): """ @param file_id: The file id @param name: Name of the parameter - + The removeFileParam function removes a name/value pair from a file upload that was added using addFileParam. """ self.callFlash('RemoveFileParam', [file_id, name]) - + def setUploadURL(self, url): """ @param url: The upload url - + Dynamically modifies the upload_url setting. """ self.callFlash('SetUploadURL', [url]) - + def setPostParams(self, paramsDict): """ @param paramsDict: Dictonary with parameters - + Dynamically modifies the post_params setting. - Any previous values are over-written. + Any previous values are over-written. """ self.callFlash('SetPostParams', [paramsDict]) - + def addPostParam(self, name, value): """ @param name: Name of the parameter @param value: Value of the parameter - + The addPostParam function adds a name/value pair that will be sent in the POST for all files uploaded. """ self.settings.addPostParam(name, value) self.setPostParams(self.settings.post_params) - + def removePostParam(self, name): """ @param name: Name of the parameter - + The removePostParam function removes a name/value pair from the values sent with the POST for file uploads. """ self.settings.removePostParam(name) self.setPostParams(self.settings.post_params) - + def setFileSizeLimit(self, fileSizeLimit): """ @param fileSizeLimit: Limit of the size for files - + Dynamically modifies the file_size_limit setting. This applies to all future files that are queued. The file_size_limit parameter will accept a unit. Valid units are B, KB, MB, and GB. The default unit is KB. @@ -288,70 +288,70 @@ def setFileSizeLimit(self, fileSizeLimit): """ self.settings.fiel_size_limit = fileSizeLimit self.callFlash('SetFileSizeLimit', [fileSizeLimit]) - + def setFileUploadLimit(self, fileUploadLimit): """ @param fileSizeLimit: Limit of the size for a upload - - Dynamically modifies the file_upload_limit setting. + + Dynamically modifies the file_upload_limit setting. The special value zero (0) indicates "no limit". """ self.settings.file_upload_limit = fileUploadLimit self.callFlash('SetFileUploadLimit', [fileUploadLimit]) - + def setFileQueueLimit(self, fileQueueLimit): """ @param fileSizeLimit: Limit of the size for a queue - + Dynamically modifies the file_queue_limit setting. The special value zero (0) indicates "no limit". """ self.settings.file_queue_limit = fileQueueLimit self.callFlash("SetFileQueueLimit", [fileQueueLimit]) - + def setFilePostName(self, filePostName): """ @param filePostName: The file post name - + Dynamically modifies the file_post_name setting. The Linux Flash Player ignores this setting. """ self.settings.file_post_name = filePostName self.callFlash("SetFilePostName", [filePostName]) - + def setButtonDisabled(self, isDisabled): """ @param isDisable: Boolean to enable/disable the button - + When 'true' changes the Flash Button state to disabled and ignores any clicks. """ self.settings.button_disabled = isDisabled self.callFlash("SetButtonDisabled", [isDisabled]) - + def setButtonAction(self, buttonAction): """ @param buttonAction: button action - + Sets the action taken when the Flash button is clicked. Valid action values are taken from the BUTTON_ACTION dict. """ self.settings.button_action = buttonAction self.callFlash("SetButtonAction", [buttonAction]) - + def setButtonCursor(self, cursor): """ - @param cursor: mouse cursor - + @param cursor: mouse cursor + Sets the mouse cursor shown when hovering over the Flash button. Valid cursor values are taken from the CURSOR dict. """ self.settings.button_cursor = cursor self.callFlash("SetButtonCursor", [cursor]) - + def setButtonText(self, html): """ @param html: Html-text for the button - + Sets the text that should be displayed over the Flash button. Text that is too large and overflows the button size will be clipped. The text can be styled using HTML supported by the Flash Player. @@ -364,17 +364,17 @@ def setButtonTextPadding(self, left, top): """ @param left: left padding @param top: top padding - + Sets the top and left padding of the Flash button text. The values may be negative. """ self.settings.button_text_top_padding = top self.settings.button_text_left_padding = left self.callFlash("SetButtonTextPadding", [left, top]) - + def setButtonTextStyle(self, css): """ @param css: CSS styles for the button text - + Sets the CSS styles used to style the Flash Button Text. CSS should be formatted according to the Flash Player documentation (Adobe Documentation) Style classes defined here can then be referenced by HTML in the button_text setting. @@ -387,7 +387,7 @@ def setButtonDimensions(self, width, height): """ @param width: The width of the button @param height: The height of the button - + Dynamically change the Flash button's width and height. The values should be numeric and should not include any units. The height value should be 1/4th of the total button image height so the button state sprite images can be @@ -400,11 +400,11 @@ def setButtonDimensions(self, width, height): DOM.setStyleAttribute(movie, 'width', width + 'px') DOM.setStyleAttribute(movie, 'height', height + 'px') self.callFlash("SetButtonDimensions", [width, height]) - + def setButtonImageURL(self, buttonImageURL): """ @param buttonImageURL: The image url for the button - + Dynamically change the image used in the Flash Button. The image url must be relative to the swfupload.swf file, an absolute path (e.g., starting with a /), or a fully qualified url. Any image format supported by Flash can be loaded. @@ -412,7 +412,7 @@ def setButtonImageURL(self, buttonImageURL): The button image is expected to be a button sprite (or a single image file with several images stacked together). The image will be used to represent all the button states by moving the image up or down to only display the needed portion. - These states include: normal, hover, click, disabled. + These states include: normal, hover, click, disabled. """ self.settings.button_image_url = buttonImageURL self.callFlash("SetButtonImageURL", [buttonImageURL]) @@ -423,73 +423,73 @@ def testExternalInterface(self): return self.callFlash("TestExternalInterface") except: return False - + def flashReady(self): """ Event-Method called by swfupload """ self.swfUploadLoaded() - + def swfUploadLoaded(self): """ Event-Method called by swfupload """ DeferredHandler.add(self.settings.swfupload_loaded_handler) - + def uploadProgress(self, file, bytesLoaded, totalBytes): """ Event-Method called by swfupload """ file = SWFFile(file) DeferredHandler.add(self.settings.upload_progress_handler, [file, bytesLoaded, totalBytes]) - + def uploadError(self, file, errorCode, message): """ Event-Method called by swfupload """ file = SWFFile(file) DeferredHandler.add(self.settings.upload_error_handler, [file, errorCode, message]) - + def uploadSuccess(self, file, receivedResponse, serverData): """ Event-Method called by swfupload """ file = SWFFile(file) DeferredHandler.add(self.settings.upload_success_handler, [file, receivedResponse, serverData]) - + def uploadComplete(self, file): """ Event-Method called by swfupload """ file = SWFFile(file) DeferredHandler.add(self.settings.upload_complete_handler, [file]) - + def fileDialogStart(self): """ Event-Method called by swfupload """ DeferredHandler.add(self.settings.file_dialog_start_handler) - + def fileQueued(self, file): """ Event-Method called by swfupload """ file = SWFFile(file) DeferredHandler.add(self.settings.file_queued_handler, [file]) - + def fileQueueError(self, file, errorCode, message): """ Event-Method called by swfupload """ file = SWFFile(file) DeferredHandler.add(self.settings.file_queue_error_handler, [file, errorCode, message]) - + def fileDialogComplete(self, sel, qu, tqu): """ Event-Method called by swfupload """ DeferredHandler.add(self.settings.file_dialog_complete_handler, [sel, qu, tqu]) - + def uploadStart(self, file): """ Event-Method called by swfupload @@ -497,13 +497,13 @@ def uploadStart(self, file): file = SWFFile(file) status = self.settings.upload_start_handler(file) self.callFlash('ReturnUploadStart', [status]) - - + + class Settings: """ - + """ - + def __init__(self): # Upload backend settings self.upload_url = "" @@ -548,7 +548,7 @@ def __init__(self): All the events associated with a failed upload are still called and so the requeuing the failed upload can conflict with the Queue Plugin (or custom code that uploads the entire queue). Code that automatically uploads the next file in the queue will upload the failed file over and over - again if care is not taken to allow the failing upload to be cancelled. + again if care is not taken to allow the failing upload to be cancelled. """ self.http_success = [] """ @@ -556,7 +556,7 @@ def __init__(self): Also, only the 200 status code provides the serverData. When returning and accepting an HTTP Status Code other than 200 it is not necessary for the server - to return content. + to return content. """ self.assume_success_timeout = 0 """ @@ -569,9 +569,9 @@ def __init__(self): uploadProgress event. A timeout of zero (0) seconds disables this feature and is the default value. SWFUpload will wait indefinitely - for the Flash Player to trigger the uploadSuccess event. + for the Flash Player to trigger the uploadSuccess event. """ - + # File Settings self.file_types = '*.*' """ @@ -580,7 +580,7 @@ def __init__(self): """ self.file_types_description = 'All Files' """ - A text description that is displayed to the user in the File Browser dialog. + A text description that is displayed to the user in the File Browser dialog. """ self.file_size_limit = 0 """ @@ -608,12 +608,12 @@ def __init__(self): errored, or cancelled a new files can be queued in its place until the queue limit has been reached. If the upload limit (or remaining uploads allowed) is less than the queue limit then the lower number is used. """ - + # Flash Settings self.flash_url = 'swfupload.swf' """ The full, absolute, or relative URL to the Flash Control swf file. This setting cannot be changed once the - SWFUpload has been instantiated. Relative URLs are relative to the page URL. + SWFUpload has been instantiated. Relative URLs are relative to the page URL. """ self.prevent_swf_caching = True """ @@ -623,7 +623,7 @@ def __init__(self): Note: The algorithm for adding the random number to the URL is dumb and cannot handle URLs that already have some parameters. """ - + # Button Settings self.button_image_url = '' """ @@ -680,7 +680,7 @@ def __init__(self): """ Sets the WMODE property of the Flash Movie. """ - + # Event Handlers self.return_upload_start_handler = None self.swfupload_loaded_handler = None @@ -688,293 +688,293 @@ def __init__(self): self.file_queued_handler = None self.file_queue_error_handler = None self.file_dialog_complete_handler = None - + self.upload_start_handler = None self.upload_progress_handler = None self.upload_error_handler = None self.upload_success_handler = None self.upload_complete_handler = None - + #self.debug_handler = self.debugMessage - + # Other settings self.custom_settings = {} self.customSettings = self.custom_settings - + # Update the flash url if needed if self.prevent_swf_caching: # TODO pass #self.flash_url = self.flash_url + self.flash_url.indexOf("?") < 0 ? "?" : "&") + "preventswfcaching=" + new Date().getTime() - + def setURL(self, url): """ @param url: The upload url """ self.upload_url = url - + def getURL(self): """ @return: the upload url """ return self.upload_url - + def setSuccessTimeout(self, assume_success_timeout): """ @param assume_success_timeout: The success timeout """ self.assume_success_timeout = assume_success_timeout - + def getSuccessTimeout(self): """ @return: the success timeout """ return self.assume_success_timeout - + def setFilePostName(self, file_post_name): """ @param file_post_name: The file post name """ self.file_post_name = file_post_name - + def getFilePostName(self): """ @return: the file post name """ return self.file_post_name - + def setPostParams(self, post_params): """ @param post_params: Dictonary with post parameters """ self.post_params = post_params - + def addPostParam(self, name, value): """ @param name: Name of the parameter @param value: Value of the parameter """ self.post_params[name] = value - + def removePostParam(self, name): pass # TODO - + def getPostParams(self): """ @return: the post parameters """ return self.post_params - + def setPreventSWFCaching(self, prevent_swf_caching): """ @param prevent_swf_caching: Boolean if prevent swf caching """ self.prevent_swf_caching = prevent_swf_caching - + def getPreventSWFCaching(self): """ @return: if prevent swf caching """ return self.prevent_swf_caching - + def useQueryString(self, use_query_string): """ @param use_query_string: Boolean if to use a query string """ self.use_query_string = use_query_string - + def isUseQueryString(self): """ @return: if to use a query string """ return self.use_query_string - + def setRequeueOnError(self, requeue_on_error): self.requeue_on_error = requeue_on_error - + def getRequeueOnError(self): return self.requeue_on_error - + def setHTTPSuccess(self, http_success): """ @param http_success: List with http success codes """ self.http_success = http_success - + def getHTTPSuccess(self): """ @return: the http success codes """ return self.http_success - + def setFileSizeLimit(self, file_size_limit): """ @param file_size_limit: Fiel size limit """ self.file_size_limit = file_size_limit - + def getFileSizeLimit(self): """ @return: the file size limit """ return self.file_size_limit - + def setFileType(self, file_types): """ @param file_types: The type(s) of files """ self.file_types = file_types - + def getFileType(self): """ @return: the type(s) of files """ return self.file_types - + def setFileTypeDescription(self, file_types_description): """ @param file_types_description: File type description """ self.file_types_description = file_types_description - + def getFileTypeDescription(self): """ @return: the file type description """ return self.file_types_description - + def setFileUploadLimit(self, file_upload_limit): """ @param file_upload_limit: File upload limit """ self.file_upload_limit = file_upload_limit - + def getFileUploadLimit(self): """ @return: the file upload limit """ return self.file_upload_limit - + def setFileQueueLimit(self, file_queue_limit): """ @param file_queue_limit: File queue limit """ self.file_queue_limit = file_queue_limit - + def getFileQueueLimit(self): """ @return: the file queue limit """ return self.file_queue_limit - + def setButtonImageURL(self, button_image_url): """ @param button_image_url: Buttons image url """ self.button_image_url = button_image_url - + def getButtonImageURL(self): """ @return: the buttons image url """ return self.button_image_url - + def setButtonWidth(self, button_width): """ @param button_width: The width of the button """ self.button_width = button_width - + def getButtonWidth(self): """ @return: the width of the button """ return self.button_width - + def setButtonHeight(self, button_height): """ @param button_height: The height of the button """ self.button_height = button_height - + def getButtonHeight(self): """ @return: the the height of the button """ return self.button_height - + def setButtonAction(self, button_action): """ @param button_action: Button action """ self.button_action = button_action - + def getButtonAction(self): """ @return: thebutton action """ return self.button_action - + def setButtonHTML(self, button_text): """ @param button_text: Buttons html text """ self.button_text = button_text - + def getButtonHTML(self): """ @return: the buttons html text """ return self.button_text - + def setButtonCSS(self, button_text_style): """ @param button_text_style: CSS Style for buttons text """ self.button_text_style = button_text_style - + def getButtonCSS(self): """ @return: the buttons css style """ return self.button_text_style - + def setButtonTopPadding(self, button_text_top_padding): """ @param button_text_top_padding: Buttons top padding """ self.button_text_top_padding = button_text_top_padding - + def getButtonTopPadding(self): """ @return: the buttons top padding """ return self.button_text_top_padding - + def setButtonLeftPadding(self, button_text_left_padding): """ @param button_text_left_padding: Buttons left padding """ self.button_text_left_padding = button_text_left_padding - + def getButtonLeftPadding(self): """ @return: the buttons left padding """ return self.button_text_left_padding - + def setFlashURL(self, flash_url): """ @param flash_url: The flash url """ self.flash_url = flash_url - + def getFlashURL(self): """ @return: the flash url """ return self.flash_url - + def setEventListener(self, listener): """ @param listener: The listener object @@ -989,7 +989,7 @@ def setEventListener(self, listener): self.file_queue_error_handler = getattr(listener, 'fileQueueError') self.file_dialog_complete_handler = getattr(listener, 'fileDialogComplete') self.upload_start_handler = getattr(listener, 'uploadStart') - + class SWFFile: """ @@ -997,7 +997,7 @@ class SWFFile: Some operating systems do not fill in all the values (this is especially true for the createdate and modificationdate values). """ - + def __init__(self, file): ### Workaround - otherwise name is undefined ### name = None @@ -1005,27 +1005,27 @@ def __init__(self, file): @{{name}} = @{{file}}.name; """) ################################################# - + self.id = file.id """ - SWFUpload file id, used for starting or cancelling and upload + SWFUpload file id, used for starting or cancelling and upload """ if name: self.name = name #file.name """ - The file name. The path is not included. + The file name. The path is not included. """ self.creationdate = file.creationdate """ - The date the file was created + The date the file was created """ self.modificationdate = file.modificationdate """ - The date the file was last modified + The date the file was last modified """ self.type = file.type """ - The file type as reported by the client operating system + The file type as reported by the client operating system """ self.index = file.index """ @@ -1033,11 +1033,11 @@ def __init__(self, file): """ self.filestatus = file.filestatus """ - The file's current status. Use SWFUpload.FILE_STATUS to interpret the value. + The file's current status. Use SWFUpload.FILE_STATUS to interpret the value. """ self.size = file.size """ - The file size in bytes + The file size in bytes """ def getId(self): @@ -1087,20 +1087,20 @@ def getSize(self): @return: the file size """ return self.size - - + + class SWFUploadInterface: """ Interface for events fired by swfupload """ - + def swfUploadLoaded(self): """ The swfUploadLoaded event is fired by flashReady. It is settable. swfUploadLoaded is called to let you know that it is safe to call SWFUpload methods. """ pass - + def uploadProgress(self, file, bytesLoaded, totalBytes): """ The uploadProgress event is fired periodically by the Flash Control. @@ -1111,7 +1111,7 @@ def uploadProgress(self, file, bytesLoaded, totalBytes): This is a bug in the Linux Flash Player. """ pass - + def uploadError(self, file, errorCode, message): """ The uploadError event is fired any time an upload is interrupted or does not @@ -1122,8 +1122,8 @@ def uploadError(self, file, errorCode, message): Upload error will not fire for files that are cancelled but still waiting in the queue. """ pass - - def uploadSuccess(self, file, receivedResponse, serverData): + + def uploadSuccess(self, file, receivedResponse, serverData): """ uploadSuccess is fired when the entire upload has been transmitted and the server returns a HTTP 200 status code. Any data outputted by the server is available in the server data parameter. @@ -1138,8 +1138,8 @@ def uploadSuccess(self, file, receivedResponse, serverData): At this point the upload is not yet complete. Another upload cannot be started from uploadSuccess. """ pass - - def uploadComplete(self, file): + + def uploadComplete(self, file): """ uploadComplete is always fired at the end of an upload cycle (after uploadError or uploadSuccess). At this point the upload is complete and another upload can be started. @@ -1149,23 +1149,23 @@ def uploadComplete(self, file): all the uploads in a queue. """ pass - - def fileDialogStart(self): + + def fileDialogStart(self): """ fileDialogStart is fired after selectFile for selectFiles is called. This event is fired immediately before the File Selection Dialog window is displayed. However, the event may not execute until after the Dialog window is closed. """ pass - - def fileQueued(self, file): + + def fileQueued(self, file): """ The fileQueued event is fired for each file that is queued after the File Selection Dialog window is closed. """ pass - - def fileQueueError(self, file, errorCode, message): + + def fileQueueError(self, file, errorCode, message): """ The fileQueueError event is fired for each file that was not queued after the File Selection Dialog window is closed. A file may not be queued for several reasons @@ -1174,8 +1174,8 @@ def fileQueueError(self, file, errorCode, message): SWFUpload.QUEUE_ERROR dict. """ pass - - def fileDialogComplete(self, sel, qu, tqu): + + def fileDialogComplete(self, sel, qu, tqu): """ The fileDialogComplete event fires after the File Selection Dialog window has been closed and all the selected files have been processed. The 'number of files queued' argument indicates the number of files that were @@ -1184,8 +1184,8 @@ def fileDialogComplete(self, sel, qu, tqu): If you want file uploading to begin automatically this is a good place to call 'startUpload()' """ pass - - def uploadStart(self, file): + + def uploadStart(self, file): """ uploadStart is called immediately before the file is uploaded. This event provides an opportunity to perform any last minute validation, add post params or do any other work before the file is uploaded. diff --git a/addons/TinyMCEditor.py b/addons/TinyMCEditor.py index e766d3062..68fef2f76 100644 --- a/addons/TinyMCEditor.py +++ b/addons/TinyMCEditor.py @@ -17,7 +17,7 @@ from pyjamas.ui import HasAlignment from pyjamas.ui.HorizontalPanel import HorizontalPanel -from pyjamas import DeferredCommand +from pyjamas import DeferredCommand from pyjamas.Timer import Timer from pyjamas import DOM diff --git a/contrib/copyright_check.py b/contrib/copyright_check.py index 0573db0b6..c52c87621 100644 --- a/contrib/copyright_check.py +++ b/contrib/copyright_check.py @@ -4,7 +4,7 @@ this program tells you which copyright holders you missed. Limitations: - + * for each section, you must put the full set of copyright holders. whilst the file lists are "carried over" i.e. later sections override earlier ones (see "remove_files()"), the same trick is @@ -287,7 +287,7 @@ def check_copyright_matches(self): for j in range(i): #print i, j, copyright_sects[i].file_pattern, copyright_sects[j].file_pattern copyright_sects[j].remove_files(copyright_sects[i].files) - + for dc in copyright_sects: dc.read_files_for_copyrights() dc.check_copyright_matches() diff --git a/contrib/create_imports.py b/contrib/create_imports.py index 69a09b0a5..5643bca48 100644 --- a/contrib/create_imports.py +++ b/contrib/create_imports.py @@ -158,7 +158,7 @@ def createImportLines(self, base=None, import_names=None): lines.append(')') self.import_lines[:] = lines return lines - + def createDestination(self, dstFile=None, import_lines=None): if dstFile is None: dstFile = self.dstFile @@ -216,8 +216,8 @@ def createDestination(self, dstFile=None, import_lines=None): srcFile = os.path.join(dirname, sys.argv[1]) dstFile = os.path.join(dirname, sys.argv[2]) ci = CreateImports( - srcFile, - dstFile, + srcFile, + dstFile, base_directory=options.base_directory, ) ci.getImportNames() @@ -235,8 +235,8 @@ def createDestination(self, dstFile=None, import_lines=None): srcFile = os.path.join(dirname, f) dstFile = srcFile.replace(gwtbase, pyjsbase) ci = CreateImports( - srcFile, - dstFile, + srcFile, + dstFile, base_directory=options.base_directory, ) ci.getImportNames() diff --git a/contrib/java2py.py b/contrib/java2py.py index e012f455b..4f5245ff6 100644 --- a/contrib/java2py.py +++ b/contrib/java2py.py @@ -223,7 +223,7 @@ def java_linemap(fn, lines): in_stupid_js = True res.append(l) continue - + res.append(fn(l)) return res diff --git a/contrib/pyjscompressor.py b/contrib/pyjscompressor.py index 835a9b2f2..0cfce23de 100644 --- a/contrib/pyjscompressor.py +++ b/contrib/pyjscompressor.py @@ -37,11 +37,11 @@ def compress_css(css_file): css_output_file = 'temp/%s.ccss' % os.path.basename(css_file) f = open(css_file) css = f.read() - + css = re.sub(r"\s+([!{};:>+\(\)\],])", r"\1", css) css = re.sub(r"([!{}:;>+\(\[,])\s+", r"\1", css) css = re.sub(r"\s+", " ", css) - + f = open(css_output_file, 'w') f.write(css) f.close() @@ -53,9 +53,9 @@ def compress_js(js_file): sys.stdout.write('Compressing %-40s' % js_file) sys.stdout.flush() js_output_file = 'temp/%s.cjs' % os.path.basename(js_file) - + compile(js_file, js_output_file) - + print '%4.1f%%' % getcompression(getsize(js_file), getsize(js_output_file)) os.rename(js_output_file, js_file) os.system('rm -f temp/*') @@ -66,14 +66,14 @@ def compress_html(html_file): js_file = 'temp/pyjs%d.js' js_output_file = 'temp/pyjs%d.cjs' html_output_file = 'temp/compiled.html' - + f = open(html_file) html = f.read() f.close() - + # remove comments betn ' % template % \ (len(scripts)-1) html = SCRIPT.sub(script_repl, html) - + # save js files in temp dir and compile them with simple optimizations for i, script in enumerate(scripts): f = open(js_file % i, 'w') f.write(script) f.close() compile(js_file % i, js_output_file % i, html_file) - + # now write all compiled js back to html file for i in xrange(len(scripts)): f = open(js_output_file % i) script = f.read() f.close() html = html.replace(template % i, script) - + f = open(html_output_file, 'w') f.write(html) f.close() @@ -129,13 +129,13 @@ def compress_all(path): sys.exit('environment variable COMPILER is not defined.\n' 'In bash, export ' 'COMPILER=/home/me/google/compiler/compiler.jar') - + if not os.path.exists('temp'): os.makedirs('temp') - + print '%17s %45s' % ('Files', 'Compression') p_size = getsize(path) - + if os.path.isfile(path): compress(path) else: @@ -145,10 +145,10 @@ def compress_all(path): for file in files: compress(os.path.join(root, file)) n_size = getsize(path) - + n_size = getsize(path) compression = getcompression(p_size, n_size) - + os.system('rm -rf temp') sizes = "Initial size: %.1fKB Final size: %.1fKB" % \ (p_size/1024., n_size/1024.) diff --git a/doc/book/Bookreader.py b/doc/book/Bookreader.py index 083fd4b6d..0bbf2f80e 100644 --- a/doc/book/Bookreader.py +++ b/doc/book/Bookreader.py @@ -47,7 +47,7 @@ def loadChapters(self): self.description = HTML() self.sink_list = SinkList() self.panel = DockPanel() - + self.loadSinks() self.sinkContainer = DockPanel() self.sinkContainer.setStyleName("ks-Sink") @@ -134,7 +134,7 @@ def show(self, info, affectHistory): self.sinkContainer.setCellVerticalAlignment(self.curSink, HasAlignment.ALIGN_TOP) self.curSink.onShow() - + def loadSinks(self): HTTPRequest().asyncGet("contents.txt", ChapterListLoader(self)) diff --git a/doc/book/Chapter.py b/doc/book/Chapter.py index 4835bf988..9b8c9028f 100644 --- a/doc/book/Chapter.py +++ b/doc/book/Chapter.py @@ -66,7 +66,7 @@ def sect_markup(txt, name): p.add(l, i) return p - + def urlmap(txt, esc=1): idx = txt.find("http://") if idx == -1: @@ -97,7 +97,7 @@ def urlmap(txt, esc=1): txt = escape(beg, esc) + "" % url txt += "%s" % escape(url) + urlmap(end, esc) return txt - + def ts(txt, esc=1): l = txt.split('\n') r = [] @@ -121,7 +121,7 @@ def __init__(self): def onShow(self): if self.loaded: - return + return self.name = self.name.replace(" ", "_") self.name = self.name.lower() @@ -177,7 +177,7 @@ def process_line(self, line): self.txt += line self.txt += "\n" return - + line = line.strip() ul_line = False ul_line2 = False @@ -247,7 +247,7 @@ def onError(self, text, code): self.vp.add(HTML("TODO: Chapter '%s' not loaded" % self.name)) self.vp.add(HTML(text)) self.vp.add(HTML(code)) - + def init(name, desc): return SinkInfo(name, desc, Chapter) diff --git a/doc/book/Sink.py b/doc/book/Sink.py index 991c41569..8c556d95c 100644 --- a/doc/book/Sink.py +++ b/doc/book/Sink.py @@ -3,10 +3,10 @@ class Sink(Composite): def __init__(self): Composite.__init__(self) - + def onHide(self): pass - + def onShow(self): pass @@ -32,7 +32,7 @@ def getInstance(self): if self.instance==None: self.instance=self.createInstance() return self.instance - + def getName(self): return self.name - + diff --git a/doc/book/SinkList.py b/doc/book/SinkList.py index 0e0808f2d..33a4ef69b 100644 --- a/doc/book/SinkList.py +++ b/doc/book/SinkList.py @@ -11,7 +11,7 @@ def __init__(self): self.vp_list=VerticalPanel() self.sinks=[] self.selectedSink=-1 - + self.sp = ScrollPanel(self.vp_list) self.sp.setWidth("14em") diff --git a/doc/gendocs.py b/doc/gendocs.py index 919a2e9a1..64f02da50 100644 --- a/doc/gendocs.py +++ b/doc/gendocs.py @@ -1,60 +1,60 @@ - -""" -Usage: - -epydoc [--html|--pdf] [-o DIR] [--parse-only|--introspect-only] [-v|-q] - [--name NAME] [--url URL] [--docformat NAME] [--graph GRAPHTYPE] - [--inheritance STYLE] [--config FILE] OBJECTS... -OBJECTS... -A list of the Python objects that should be documented. Objects can be specified using dotted names (such as os.path), module filenames (such as epydoc/epytext.py), or package directory names (such as epydoc/). Packages are expanded to include all sub-modules and sub-packages. - ---html Generate HTML output. (default) ---pdf Generate Adobe Acrobat (PDF) output, using LaTeX. --o DIR, --output DIR, --target DIR - The output directory. ---parse-only, --introspect-only - By default, epydoc will gather information about each Python object using two methods: parsing the object's source code; and importing the object and directly introspecting it. Epydoc combines the information obtained from these two methods to provide more complete and accurate documentation. However, if you wish, you can tell epydoc to use only one or the other of these methods. For example, if you are running epydoc on untrusted code, you should use the --parse-only option. --v, -q Increase (-v) or decrease (-q) the verbosity of the output. These options may be repeated to further increase or decrease verbosity. Docstring markup warnings are supressed unless -v is used at least once. ---name NAME The documented project's name. ---url URL The documented project's URL. ---docformat NAME - The markup language that should be used by default to process modules' docstrings. This is only used for modules that do not define the special __docformat__ variable; it is recommended that you explicitly specify __docformat__ in all your modules. ---graph GRAPHTYPE - -Include graphs of type GRAPHTYPE in the generated output. Graphs are generated using the Graphviz dot executable. If this executable is not on the path, then use --dotpath to specify its location. This option may be repeated to include multiple graph types in the output. To include all graphs, use --graph all. The available graph types are: -classtree: displays each class's base classes and subclasses; -callgraph: displays the callers and callees of each function or method. These graphs are based on profiling information, which must be specified using the --pstate option. -umlclass: displays each class's base classes and subclasses, using UML style. Methods and attributes are listed in the classes where they are defined. If type information is available about attributes (via the @type field), then those types are displayed as separate classes, and the attributes are displayed as associations. ---inheritance STYLE - -The format that should be used to display inherited methods, variables, and properties. Currently, three styles are supported. To see an example of each style, click on it: -grouped: Inherited objects are gathered into groups, based on which class they are inherited from. -listed: Inherited objects are listed in a short list at the end of the summary table. -included: Inherited objects are mixed in with non-inherited objects. ---config FILE Read the given configuration file, which can contain both options and Python object names. This option may be used multiple times, if you wish to use multiple configuration files. See Configuration Files for more information. -""" - -import glob -from os.path import abspath, pathsep -import os -paths = glob.glob(abspath('../library/pyjamas/*.py')) + \ - glob.glob(abspath('../library/pyjamas/ui/*.py')) + \ - glob.glob(abspath('../library/pyjamas/Canvas/*.py')) + \ - glob.glob(abspath('../bin/*.py')) -print paths -command = ['epydoc', "-v", "-v", - '--parse-only', - '--html', - '-o', 'api', - '--name', 'Pyjamas', - '--url', 'http://pyjs.org', - ]+list(paths) - -def quote_shell(x): - if x.find(" ") != -1: - return '"'+x+'"' - return x -commandString = ' '.join(map(quote_shell, command)) -from os import system -print '>>', commandString -system(commandString) + +""" +Usage: + +epydoc [--html|--pdf] [-o DIR] [--parse-only|--introspect-only] [-v|-q] + [--name NAME] [--url URL] [--docformat NAME] [--graph GRAPHTYPE] + [--inheritance STYLE] [--config FILE] OBJECTS... +OBJECTS... +A list of the Python objects that should be documented. Objects can be specified using dotted names (such as os.path), module filenames (such as epydoc/epytext.py), or package directory names (such as epydoc/). Packages are expanded to include all sub-modules and sub-packages. + +--html Generate HTML output. (default) +--pdf Generate Adobe Acrobat (PDF) output, using LaTeX. +-o DIR, --output DIR, --target DIR + The output directory. +--parse-only, --introspect-only + By default, epydoc will gather information about each Python object using two methods: parsing the object's source code; and importing the object and directly introspecting it. Epydoc combines the information obtained from these two methods to provide more complete and accurate documentation. However, if you wish, you can tell epydoc to use only one or the other of these methods. For example, if you are running epydoc on untrusted code, you should use the --parse-only option. +-v, -q Increase (-v) or decrease (-q) the verbosity of the output. These options may be repeated to further increase or decrease verbosity. Docstring markup warnings are supressed unless -v is used at least once. +--name NAME The documented project's name. +--url URL The documented project's URL. +--docformat NAME + The markup language that should be used by default to process modules' docstrings. This is only used for modules that do not define the special __docformat__ variable; it is recommended that you explicitly specify __docformat__ in all your modules. +--graph GRAPHTYPE + +Include graphs of type GRAPHTYPE in the generated output. Graphs are generated using the Graphviz dot executable. If this executable is not on the path, then use --dotpath to specify its location. This option may be repeated to include multiple graph types in the output. To include all graphs, use --graph all. The available graph types are: +classtree: displays each class's base classes and subclasses; +callgraph: displays the callers and callees of each function or method. These graphs are based on profiling information, which must be specified using the --pstate option. +umlclass: displays each class's base classes and subclasses, using UML style. Methods and attributes are listed in the classes where they are defined. If type information is available about attributes (via the @type field), then those types are displayed as separate classes, and the attributes are displayed as associations. +--inheritance STYLE + +The format that should be used to display inherited methods, variables, and properties. Currently, three styles are supported. To see an example of each style, click on it: +grouped: Inherited objects are gathered into groups, based on which class they are inherited from. +listed: Inherited objects are listed in a short list at the end of the summary table. +included: Inherited objects are mixed in with non-inherited objects. +--config FILE Read the given configuration file, which can contain both options and Python object names. This option may be used multiple times, if you wish to use multiple configuration files. See Configuration Files for more information. +""" + +import glob +from os.path import abspath, pathsep +import os +paths = glob.glob(abspath('../library/pyjamas/*.py')) + \ + glob.glob(abspath('../library/pyjamas/ui/*.py')) + \ + glob.glob(abspath('../library/pyjamas/Canvas/*.py')) + \ + glob.glob(abspath('../bin/*.py')) +print paths +command = ['epydoc', "-v", "-v", + '--parse-only', + '--html', + '-o', 'api', + '--name', 'Pyjamas', + '--url', 'http://pyjs.org', + ]+list(paths) + +def quote_shell(x): + if x.find(" ") != -1: + return '"'+x+'"' + return x +commandString = ' '.join(map(quote_shell, command)) +from os import system +print '>>', commandString +system(commandString) diff --git a/examples/addonsgallery/AddonsGallery.py b/examples/addonsgallery/AddonsGallery.py index 495f8661c..8b7d229bf 100644 --- a/examples/addonsgallery/AddonsGallery.py +++ b/examples/addonsgallery/AddonsGallery.py @@ -32,7 +32,7 @@ def onModuleLoad(self): self.description=HTML() self.sink_list=SinkList() self.panel=DockPanel() - + self.loadSinks() self.sinkContainer = DockPanel() self.sinkContainer.setStyleName("ks-Sink") @@ -58,7 +58,7 @@ def onModuleLoad(self): self.onHistoryChanged(initToken) else: self.showIntro() - + def show(self, info, affectHistory=None): if info == self.curInfo: return self.curInfo = info @@ -79,7 +79,7 @@ def show(self, info, affectHistory=None): self.sinkContainer.setCellHeight(self.curSink, "100%") self.sinkContainer.setCellVerticalAlignment(self.curSink, HasAlignment.ALIGN_TOP) self.curSink.onShow() - + def loadSinks(self): self.sink_list.add(IntroTab.init()) self.sink_list.add(TooltipTab.init()) diff --git a/examples/addonsgallery/AutoCompleteTab.py b/examples/addonsgallery/AutoCompleteTab.py index e06aca0e0..2b6f66455 100644 --- a/examples/addonsgallery/AutoCompleteTab.py +++ b/examples/addonsgallery/AutoCompleteTab.py @@ -11,14 +11,14 @@ def __init__(self): Sink.__init__(self) self.colour_input = AutoCompleteTextBox() self.colour_input.setCompletionItems(colours) - + panel = HorizontalPanel() panel.add(HTML("Enter a colour: ")) panel.add(self.colour_input) panel.setSpacing(8) self.setWidget(panel) - + def onShow(self): #self.colour_input.setFocus(True) diff --git a/examples/addonsgallery/Canvas2DTab.py b/examples/addonsgallery/Canvas2DTab.py index f32cb3e84..c1db158d9 100644 --- a/examples/addonsgallery/Canvas2DTab.py +++ b/examples/addonsgallery/Canvas2DTab.py @@ -13,19 +13,19 @@ class CanvasTab(Sink): def __init__(self): Sink.__init__(self) colour_grid = ColourGridCanvas() - rotated = RotatedCanvas() + rotated = RotatedCanvas() spheres = SpheresCanvas() pattern = PatternCanvas() spiro = SpiroCanvas() self.solar = SolarCanvas() - + row0 = HorizontalPanel() row0.setSpacing(8) row0.add(colour_grid) row0.add(rotated) row0.add(spheres) row0.add(pattern) - + row1 = HorizontalPanel() row1.setSpacing(8) row1.add(self.solar) @@ -40,7 +40,7 @@ def __init__(self): def onShow(self): self.solar.isActive = True self.solar.onTimer() - + def onHide(self): self.solar.isActive = False @@ -50,18 +50,18 @@ def init(): Canvas vector drawing component: Canvas2D

Gives python access to the browser's native canvas tag. -

There are two canvas drawing libraries: Canvas2D (oldest) and Canvas -(preferred). Both work in modern browsers (that support canvas). For IE +

There are two canvas drawing libraries: Canvas2D (oldest) and Canvas +(preferred). Both work in modern browsers (that support canvas). For IE the canvas functionality is emulated in javascript. This leads to -lower performance in IE and missing/broken functionality. Canvas2D -depends on Explorer Canvas +lower performance in IE and missing/broken functionality. Canvas2D +depends on Explorer Canvas in IE.

Originally by Alexei Sokolov at gwt.components.googlepages.com" -
Samples ported from the Mozilla canvas tutorial" +
Samples ported from the Mozilla canvas tutorial"
Samples ported from the Mozilla canvas tutorial -""" - +""" + return SinkInfo("Canvas2D", text, CanvasTab) @@ -71,7 +71,7 @@ def __init__(self): self.draw() self.addMouseListener(self) self.addKeyboardListener(self) - + def draw(self): for i in range(0, 6): for j in range(0, 6): @@ -83,11 +83,11 @@ def onMouseDown(self, sender, x, y): pass def onMouseEnter(self, sender): - RootPanel().add(HTML("mouseenter: setting focus (keyboard input accepted)")) + RootPanel().add(HTML("mouseenter: setting focus (keyboard input accepted)")) self.setFocus(True) def onMouseLeave(self, sender): - RootPanel().add(HTML("mouseleave: clearing focus (keyboard input not accepted)")) + RootPanel().add(HTML("mouseleave: clearing focus (keyboard input not accepted)")) self.setFocus(False) def onMouseMove(self, sender, x, y): @@ -97,16 +97,16 @@ def onMouseUp(self, sender, x, y): pass def onKeyUp(self, sender, keyCode, modifiers): - RootPanel().add(HTML("keyup: %s" % keyCode)) - + RootPanel().add(HTML("keyup: %s" % keyCode)) + def onKeyDown(self, sender, keyCode, modifiers): - RootPanel().add(HTML("keydown: %s" % keyCode)) + RootPanel().add(HTML("keydown: %s" % keyCode)) def onClick(self, sender): - RootPanel().add(HTML("click")) + RootPanel().add(HTML("click")) def onKeyPress(self, sender, keyCode, modifiers): - RootPanel().add(HTML("keypressed: %s" % keyCode)) + RootPanel().add(HTML("keypressed: %s" % keyCode)) class RotatedCanvas(Canvas): @@ -123,7 +123,7 @@ def draw(self): self.context.fillStyle = 'rgb(%d,%d,255)'%((51*i), (255-51*i)) # draw individual dots - for j in range(0,i*6): + for j in range(0,i*6): self.context.rotate(pi*2/(i*6)) self.context.beginPath() self.context.arc(0,i*12.5,5,0,pi*2,True) @@ -136,14 +136,14 @@ class SpheresCanvas(Canvas): def __init__(self): Canvas.__init__(self, 150, 150) self.draw() - + def draw(self): # create gradients radgrad = self.context.createRadialGradient(45,45,10,52,50,30) radgrad.addColorStop(0, '#A7D30C') radgrad.addColorStop(0.9, '#019F62') radgrad.addColorStop(1, 'rgba(1,159,98,0)') - + radgrad2 = self.context.createRadialGradient(105,105,20,112,120,50) radgrad2.addColorStop(0, '#FF5F98') radgrad2.addColorStop(0.75, '#FF0188') @@ -158,7 +158,7 @@ def draw(self): radgrad4.addColorStop(0, '#F4F201') radgrad4.addColorStop(0.8, '#E4C700') radgrad4.addColorStop(1, 'rgba(228,199,0,0)') - + # draw shapes self.context.fillStyle = radgrad4 self.context.fillRect(0,0,150,150) @@ -178,7 +178,7 @@ def __init__(self): def onLoad(self, sender=None): if sender==self.img: self.draw() - + def onError(self): pass @@ -191,7 +191,7 @@ def draw(self): class SpiroCanvas(Canvas): def __init__(self): Canvas.__init__(self, 300, 300) - self.draw() + self.draw() def draw(self): self.context.fillRect(0,0,300,300) @@ -226,23 +226,23 @@ def drawSpirograph(self, R, r, O): class SolarCanvas(Canvas): def __init__(self): - Canvas.__init__(self, 300, 300) + Canvas.__init__(self, 300, 300) self.sun = CanvasImage('images/sun.png') self.moon = CanvasImage('images/moon.png') self.earth = CanvasImage('images/earth.png') - + self.loader = ImageLoadListener() self.loader.add(self.sun) self.loader.add(self.moon) - self.loader.add(self.earth) - + self.loader.add(self.earth) + self.isActive = True self.onTimer() def onTimer(self, t=None): if not self.isActive: return - + Timer(100, self) self.draw() @@ -256,35 +256,35 @@ def draw(self): pi = 3.14159265358979323 if not self.loader.isLoaded(): return - + self.context.globalCompositeOperation = 'destination-over' # clear canvas - self.context.clearRect(0,0,300,300) - + self.context.clearRect(0,0,300,300) + self.context.save() self.context.fillStyle = 'rgba(0,0,0,0.4)' self.context.strokeStyle = 'rgba(0,153,255,0.4)' self.context.translate(150,150) - + # Earth self.context.rotate( ((2*pi)/60)*self.getTimeSeconds() + ((2*pi)/60000)*self.getTimeMilliseconds() ) self.context.translate(105,0) self.context.fillRect(0,-12,50,24) # Shadow self.context.drawImage(self.earth.getElement() ,-12,-12) - + # Moon self.context.save() self.context.rotate( ((2*pi)/6)*self.getTimeSeconds() + ((2*pi)/6000)*self.getTimeMilliseconds() ) self.context.translate(0,28.5) self.context.drawImage(self.moon.getElement(),-3.5,-3.5) self.context.restore() - + self.context.restore() - + self.context.beginPath() self.context.arc(150,150,105,0,pi*2,False) # Earth orbit self.context.stroke() - + self.context.drawImage(self.sun.getElement(),0,0) diff --git a/examples/addonsgallery/CanvasTab.py b/examples/addonsgallery/CanvasTab.py index 1d3ecc556..bd2e87eb4 100644 --- a/examples/addonsgallery/CanvasTab.py +++ b/examples/addonsgallery/CanvasTab.py @@ -15,19 +15,19 @@ class CanvasTab(Sink): def __init__(self): Sink.__init__(self) colour_grid = ColourGridCanvas() - rotated = RotatedCanvas() + rotated = RotatedCanvas() spheres = SpheresCanvas() #pattern = PatternCanvas() spiro = SpiroCanvas() self.solar = SolarCanvas() - + row0 = HorizontalPanel() row0.setSpacing(8) row0.add(colour_grid) row0.add(rotated) row0.add(spheres) #row0.add(pattern) - + row1 = HorizontalPanel() row1.setSpacing(8) row1.add(self.solar) @@ -42,7 +42,7 @@ def __init__(self): def onShow(self): self.solar.isActive = True self.solar.onTimer() - + def onHide(self): self.solar.isActive = False @@ -52,16 +52,16 @@ def init(): Canvas vector drawing component: Canvas2D

Gives python access to the browser's native canvas tag. -

There are two canvas drawing libraries: Canvas2D (oldest) and Canvas -(preferred). Both work in modern browsers (that support canvas). For IE +

There are two canvas drawing libraries: Canvas2D (oldest) and Canvas +(preferred). Both work in modern browsers (that support canvas). For IE the canvas functionality is emulated in javascript. This leads to lower performance in IE and missing/broken functionality.

Originally by Alexei Sokolov at gwt.components.googlepages.com" -
Samples ported from the Mozilla canvas tutorial" +
Samples ported from the Mozilla canvas tutorial"
Samples ported from the Mozilla canvas tutorial """ - + return SinkInfo("Canvas", text, CanvasTab) @@ -71,7 +71,7 @@ def __init__(self): self.draw() self.addMouseListener(self) self.addKeyboardListener(self) - + def draw(self): for i in range(0, 6): for j in range(0, 6): @@ -84,11 +84,11 @@ def onMouseDown(self, sender, x, y): pass def onMouseEnter(self, sender): - RootPanel().add(HTML("mouseenter: setting focus (keyboard input accepted)")) + RootPanel().add(HTML("mouseenter: setting focus (keyboard input accepted)")) self.setFocus(True) def onMouseLeave(self, sender): - RootPanel().add(HTML("mouseleave: clearing focus (keyboard input not accepted)")) + RootPanel().add(HTML("mouseleave: clearing focus (keyboard input not accepted)")) self.setFocus(False) def onMouseMove(self, sender, x, y): @@ -98,16 +98,16 @@ def onMouseUp(self, sender, x, y): pass def onKeyUp(self, sender, keyCode, modifiers): - RootPanel().add(HTML("keyup: %s" % keyCode)) - + RootPanel().add(HTML("keyup: %s" % keyCode)) + def onKeyDown(self, sender, keyCode, modifiers): - RootPanel().add(HTML("keydown: %s" % keyCode)) + RootPanel().add(HTML("keydown: %s" % keyCode)) def onClick(self, sender): - RootPanel().add(HTML("click")) + RootPanel().add(HTML("click")) def onKeyPress(self, sender, keyCode, modifiers): - RootPanel().add(HTML("keypressed: %s" % keyCode)) + RootPanel().add(HTML("keypressed: %s" % keyCode)) class RotatedCanvas(GWTCanvas): @@ -124,7 +124,7 @@ def draw(self): self.setFillStyle(Color('rgb(%d,%d,255)'%((51*i), (255-51*i)))) # draw individual dots - for j in range(0,i*6): + for j in range(0,i*6): self.rotate(pi*2/(i*6)) self.beginPath() self.arc(0,i*12.5,5,0,pi*2,True) @@ -137,14 +137,14 @@ class SpheresCanvas(GWTCanvas): def __init__(self): GWTCanvas.__init__(self, 150, 150, 150, 150) self.draw() - + def draw(self): # create gradients radgrad = self.createRadialGradient(45,45,10,52,50,30) radgrad.addColorStop(0, Color('#A7D30C')) radgrad.addColorStop(0.9, Color('#019F62')) radgrad.addColorStop(1, Color('rgba(1,159,98,0)')) - + radgrad2 = self.createRadialGradient(105,105,20,112,120,50) radgrad2.addColorStop(0, Color('#FF5F98')) radgrad2.addColorStop(0.75, Color('#FF0188')) @@ -159,7 +159,7 @@ def draw(self): radgrad4.addColorStop(0, Color('#F4F201')) radgrad4.addColorStop(0.8, Color('#E4C700')) radgrad4.addColorStop(1, Color('rgba(228,199,0,0)')) - + # draw shapes self.setFillStyle(radgrad4) self.fillRect(0,0,150,150) @@ -193,7 +193,7 @@ def draw(self): class SpiroCanvas(GWTCanvas): def __init__(self): GWTCanvas.__init__(self, 300, 300, 300, 300) - self.draw() + self.draw() def draw(self): self.saveContext() @@ -239,7 +239,7 @@ def __init__(self): ], self, ) - + self.isActive = True self.onTimer() @@ -251,7 +251,7 @@ def onImagesLoaded(self, imagesHandles): def onTimer(self, t=None): if not self.isActive: return - + Timer(100, self) self.draw() @@ -265,35 +265,35 @@ def draw(self): pi = 3.14159265358979323 if not getattr(self, 'earth', None): return - + self.setGlobalCompositeOperation('destination-over') # clear canvas - self.clear() - + self.clear() + self.saveContext() self.setFillStyle(Color('rgba(0,0,0,0.4)')) self.setStrokeStyle(Color('rgba(0,153,255,0.4)')) self.translate(150,150) - + # Earth self.rotate( ((2*pi)/60)*self.getTimeSeconds() + ((2*pi)/60000)*self.getTimeMilliseconds() ) self.translate(105,0) self.fillRect(0,-12,50,24) # Shadow self.drawImage(self.earth.getElement() ,-12,-12) - + # Moon self.saveContext() self.rotate( ((2*pi)/6)*self.getTimeSeconds() + ((2*pi)/6000)*self.getTimeMilliseconds() ) self.translate(0,28.5) self.drawImage(self.moon.getElement(),-3.5,-3.5) self.restoreContext() - + self.restoreContext() - + self.beginPath() self.arc(150,150,105,0,pi*2,False) # Earth orbit self.stroke() - + self.drawImage(self.sun.getElement(),0,0) diff --git a/examples/addonsgallery/TooltipTab.py b/examples/addonsgallery/TooltipTab.py index 93dd52425..fd7ea491c 100644 --- a/examples/addonsgallery/TooltipTab.py +++ b/examples/addonsgallery/TooltipTab.py @@ -10,22 +10,22 @@ def __init__(self): Sink.__init__(self) img = Image("images/num1.png") img.addMouseListener(TooltipListener("An image: " + img.getUrl())) - + img2 = Image("images/num2.png") img2.addMouseListener(TooltipListener("An image: " + img2.getUrl())) html = HTML("Some HTML text.") html.addMouseListener(TooltipListener("An HTML component.")) - + panel_h = HorizontalPanel() panel_h.add(img) - panel_h.add(img2) + panel_h.add(img2) panel_h.setSpacing(8) - + panel = VerticalPanel() panel.add(panel_h) panel.add(html) - + panel.setSpacing(8) self.setWidget(panel) diff --git a/examples/asteroids/Space.py b/examples/asteroids/Space.py index bf49cd48c..58bceb54d 100644 --- a/examples/asteroids/Space.py +++ b/examples/asteroids/Space.py @@ -142,7 +142,7 @@ def __init__(self, w, h): self.width = w self.height = h - self.key_up = self.key_down = self.key_left = self.key_right = self.key_fire = False + self.key_up = self.key_down = self.key_left = self.key_right = self.key_fire = False images = ['./images/Ship1.png', './images/Ship2.png', './images/Asteroid.png'] loadImages(images, self) @@ -157,7 +157,7 @@ def __init__(self, w, h): self.num_asteroids = NUM_ASTEROIDS - self.sinkEvents(Event.KEYEVENTS) + self.sinkEvents(Event.KEYEVENTS) self.onTimer() def onImagesLoaded(self, imagesHandles): @@ -171,7 +171,7 @@ def onImagesLoaded(self, imagesHandles): self.reset() self.run = True - + def addTo(self, panel): panel.add(self) self.top = DOM.getAbsoluteTop(self.getElement()) @@ -280,7 +280,7 @@ def advance(self): self.yy -= self.height elif self.dy < 0 and self.yy < 0: self.yy += self.height - + def setKey(self, k, set): DOM.eventPreventDefault(DOM.eventGetCurrentEvent()) if k == KeyboardListener.KEY_UP: @@ -293,7 +293,7 @@ def setKey(self, k, set): self.key_right = set elif k == 32: self.key_fire = set - + def onKeyPress(self, sender, keyCode, modifiers = None): pass #self.setKey(keyCode, True) @@ -346,7 +346,7 @@ def reset(self): self.dy = 0 self.rot = 0 self.speed = 0 - + def draw(self): #if not self.loader.isLoaded(): diff --git a/examples/buildall.py b/examples/buildall.py index 2285939d1..ec49e3f7a 100755 --- a/examples/buildall.py +++ b/examples/buildall.py @@ -29,12 +29,12 @@ def guessMainScriptName(d): os.chdir(d) try: name = guessMainScriptName(d) - if not name: + if not name: print "Skipping directory %s because no main script found" % d continue f = name + '.py' print("********** Building %s **********" % name.upper()) - if os.path.isdir('output'): + if os.path.isdir('output'): shutil.rmtree(os.path.join(".", "output")) # Why should we skip compilation here ? Just clean first. res = os.system("python ../%s %s %s" % (pyjsbuild, options, f)) except Exception, e: @@ -42,4 +42,3 @@ def guessMainScriptName(d): finally: #raw_input('Press any key') os.chdir("..") - \ No newline at end of file diff --git a/examples/builder/Builder.py b/examples/builder/Builder.py index dee5b431c..c82439fd0 100644 --- a/examples/builder/Builder.py +++ b/examples/builder/Builder.py @@ -110,5 +110,5 @@ def onUILoadError(self, text, code): pyjd.setup("http://127.0.0.1/examples/builder/public/Builder.html?fred=foo#me") et = EventTest() HTTPUILoader(et).load("builder.xml") - + pyjd.run() diff --git a/examples/canvasprocessing/CanvasProcessing.py b/examples/canvasprocessing/CanvasProcessing.py index cfe0fa39a..cbffcb92c 100644 --- a/examples/canvasprocessing/CanvasProcessing.py +++ b/examples/canvasprocessing/CanvasProcessing.py @@ -23,7 +23,7 @@ def setup(): X = p.width / 2 Y = p.width / 2 nX = X - nY = Y + nY = Y def draw(): global p,radius,delay,X,Y,nX,nY @@ -34,7 +34,7 @@ def draw(): p.fill( 0, 121, 184 ) p.stroke(255) p.ellipse(X, Y, radius, radius ) - + def mouseMoved(): global p,nX,nY nX = p.mouseX @@ -47,7 +47,7 @@ def __init__(self): self.p = Processing (self.c) global p p = self.p - + if __name__ == '__main__': note = HTML(""" Note that this is an example of using processing.js.
diff --git a/examples/clickoverride/Override.py b/examples/clickoverride/Override.py index b46933269..b34c60633 100644 --- a/examples/clickoverride/Override.py +++ b/examples/clickoverride/Override.py @@ -31,7 +31,7 @@ def __init__(self): self.title=Text('Board') self.title.setzIndex(100) self.add(self.title) - self.setSize("100%", "50%") + self.setSize("100%", "50%") self.setBorderWidth(1) def onClick(self, sender): @@ -53,7 +53,7 @@ class Text(HTML, ClickHandler): def __init__(self, text): HTML.__init__(self, text) ClickHandler.__init__(self, preventDefault=True) - self.addClickListener(self) + self.addClickListener(self) def onClick(self, sender): log.debug('Text'+str(sender)) diff --git a/examples/cssmesser/CSSMess.py b/examples/cssmesser/CSSMess.py index 0e5c94887..ca35fd714 100644 --- a/examples/cssmesser/CSSMess.py +++ b/examples/cssmesser/CSSMess.py @@ -45,7 +45,7 @@ sc = None def greet(fred): global sc - txt = fred.getText() + txt = fred.getText() if txt == "Click me lots": sc = StyleSheetCssText(newcolours) fred.setText("Did it work?") diff --git a/examples/deprecated/gears/GearsDemo.py b/examples/deprecated/gears/GearsDemo.py index 966c1d68e..00604094a 100644 --- a/examples/deprecated/gears/GearsDemo.py +++ b/examples/deprecated/gears/GearsDemo.py @@ -47,7 +47,7 @@ def onClick(self, sender): rs.next() rs.close() - + if __name__ == '__main__': app = DbTest() diff --git a/examples/deprecated/pywebgtkbuilder/AutoGtk.py b/examples/deprecated/pywebgtkbuilder/AutoGtk.py index 5cfb3789f..1f968ad30 100644 --- a/examples/deprecated/pywebgtkbuilder/AutoGtk.py +++ b/examples/deprecated/pywebgtkbuilder/AutoGtk.py @@ -25,22 +25,22 @@ class XMLload: def onModuleLoad(self): HTTPRequest().asyncGet( - "address_form.ui", + "address_form.ui", XMLloader(self), ) def onError(self, text, code): # FIXME pass - + def onTimeout(self, text): - # FIXME + # FIXME pass - + def doStuff(self, xmldoc): b = gtk.Builder() - + b.add_from_string(xmldoc) for o in b.get_objects(): diff --git a/examples/dnd/AbsolutePositionExample.py b/examples/dnd/AbsolutePositionExample.py index e428e86ea..9157bbe44 100644 --- a/examples/dnd/AbsolutePositionExample.py +++ b/examples/dnd/AbsolutePositionExample.py @@ -28,36 +28,36 @@ # XXX must import Example class - it provides e.g.the createDraggable function class AbsolutePositionExample(Example): - + CSS_DEMO_ABSOLUTE_POSITION_EXAMPLE = "demo-AbsolutePositionExample" - + def __init__(self, dragController): Example.__init__(self, dragController) self.addStyleName(self.CSS_DEMO_ABSOLUTE_POSITION_EXAMPLE) - + # use the drop target as this composite's widget positioningDropTarget = AbsolutePanel() positioningDropTarget.setPixelSize(400, 200) self.setWidget(positioningDropTarget) - + # instantiate our drop controller self.absposdc = AbsolutePositionDropController(positioningDropTarget) dragController.registerDropController(self.absposdc) - - + + def getDescription(self): return "Draggable widgets can be placed anywhere on the gray drop target." - + def getInvolvedClasses(self): return [AbsolutePositionExample, AbsolutePositionDropController] - - + + def onInitialLoad(self): self.absposdc.drop(self.createDraggable(), 10, 30) self.absposdc.drop(self.createDraggable(), 60, 8) self.absposdc.drop(self.createDraggable(), 190, 60) - + diff --git a/examples/dynamictable/DayFilterWidget.py b/examples/dynamictable/DayFilterWidget.py index 04f8f54b8..dcac58fcd 100644 --- a/examples/dynamictable/DayFilterWidget.py +++ b/examples/dynamictable/DayFilterWidget.py @@ -18,7 +18,7 @@ def __init__(self, owner, caption, day): class DayCheckBoxListener: def __init__(self, calendar): self.calendar = calendar - + def onClick(self, sender): self.calendar.setDayIncluded(sender.day, sender.isChecked()) @@ -27,7 +27,7 @@ class DayFilterWidget(Composite): def __init__(self, calendar): Composite.__init__(self) - + self.calendar = calendar self.dayCheckBoxListener = DayCheckBoxListener(calendar) self.outer = VerticalPanel() @@ -48,17 +48,17 @@ def __init__(self, calendar): hp.setHorizontalAlignment(HasAlignment.ALIGN_CENTER) hp.add(self.buttonAll) hp.add(self.buttonNone) - + self.outer.add(hp) self.outer.setCellVerticalAlignment(hp, HasAlignment.ALIGN_BOTTOM) self.outer.setCellHorizontalAlignment(hp, HasAlignment.ALIGN_CENTER) - + def setAllCheckBoxes(self, checked): for widget in self.outer: if hasattr(widget, "setChecked"): widget.setChecked(checked) self.dayCheckBoxListener.onClick(widget) - + def onClick(self, sender): if self.buttonAll == sender: self.setAllCheckBoxes(True) @@ -66,5 +66,5 @@ def onClick(self, sender): self.setAllCheckBoxes(False) - - + + diff --git a/examples/dynamictable/DynaTable.py b/examples/dynamictable/DynaTable.py index 0908cda57..4865046be 100644 --- a/examples/dynamictable/DynaTable.py +++ b/examples/dynamictable/DynaTable.py @@ -11,7 +11,7 @@ def onModuleLoad(self): if slot is not None: calendar = SchoolCalendarWidget(15) slot.add(calendar) - + slot = RootPanel("days") if slot is not None: filterWidget = DayFilterWidget(calendar) diff --git a/examples/dynamictable/DynaTableWidget.py b/examples/dynamictable/DynaTableWidget.py index bbf0641cd..4de4c8354 100644 --- a/examples/dynamictable/DynaTableWidget.py +++ b/examples/dynamictable/DynaTableWidget.py @@ -18,11 +18,11 @@ def __init__(self, owner): self.gotoNext = Button(">", self) self.gotoPrev = Button("<", self) self.status = HTML() - + self.initWidget(self.bar) self.bar.setStyleName("navbar") self.status.setStyleName("status") - + buttons = HorizontalPanel() buttons.add(self.gotoFirst) buttons.add(self.gotoPrev) @@ -34,10 +34,10 @@ def __init__(self, owner): self.bar.setCellHorizontalAlignment(self.status, HasAlignment.ALIGN_RIGHT) self.bar.setCellVerticalAlignment(self.status, HasAlignment.ALIGN_MIDDLE) self.bar.setCellWidth(self.status, "100%") - + self.gotoPrev.setEnabled(False) self.gotoFirst.setEnabled(False) - + def onClick(self, sender): if sender == self.gotoNext: self.owner.startRow += self.owner.getDataRowCount() @@ -60,40 +60,40 @@ def __init__(self, owner): def accept(self, startRow, data): destRowCount = self.owner.getDataRowCount() destColCount = self.owner.grid.getCellCount(0) - + srcRowIndex = 0 srcRowCount = len(data) destRowIndex = 1 - + while srcRowIndex < srcRowCount: - + srcRowData = data[srcRowIndex] - + for srcColIndex in range(destColCount): cellHTML = srcRowData[srcColIndex] self.owner.grid.setText(destRowIndex, srcColIndex, cellHTML) - + srcRowIndex += 1 destRowIndex += 1 - + isLastPage = False - + while destRowIndex < destRowCount + 1: - + isLastPage = True - + for destColIndex in range(destColCount): self.owner.grid.clearCell(destRowIndex, destColIndex) - + destRowIndex += 1 - + self.owner.navbar.gotoNext.setEnabled(not isLastPage) self.owner.navbar.gotoFirst.setEnabled(startRow > 0) self.owner.navbar.gotoPrev.setEnabled(startRow > 0) - + self.owner.setStatusText(str(startRow + 1) + " - " + str(startRow + srcRowCount)) - - def failed(self, message): + + def failed(self, message): msg = "Failed to access data" if message: msg = "%s: %s" % (msg, message) @@ -105,13 +105,13 @@ class DynaTableWidget(Composite): def __init__(self, provider, columns, columnStyles, rowCount): Composite.__init__(self) - + self.acceptor = RowDataAcceptorImpl(self) self.outer = DockPanel() self.startRow = 0 self.grid = Grid() self.navbar = NavBar(self) - + self.provider = provider self.initWidget(self.outer) self.grid.setStyleName("table") @@ -119,7 +119,7 @@ def __init__(self, provider, columns, columnStyles, rowCount): self.outer.add(self.grid, DockPanel.CENTER) self.initTable(columns, columnStyles, rowCount) self.setStyleName("DynaTable-DynaTableWidget") - + def initTable(self, columns, columnStyles, rowCount): self.grid.resize(rowCount + 1, len(columns)) for i in range(len(columns)): @@ -129,20 +129,20 @@ def initTable(self, columns, columnStyles, rowCount): def setStatusText(self, text): self.navbar.status.setText(text) - + def clearStatusText(self, text): self.navbar.status.setHTML(" ") - + def refresh(self): self.navbar.gotoFirst.setEnabled(False) self.navbar.gotoPrev.setEnabled(False) self.navbar.gotoNext.setEnabled(False) - + self.setStatusText("Please wait...") self.provider.updateRowData(self.startRow, self.grid.getRowCount() - 1, self.acceptor) - + def setRowCount(self, rows): self.grid.resizeRows(rows) - + def getDataRowCount(self): return self.grid.getRowCount() - 1 diff --git a/examples/dynamictable/Person.py b/examples/dynamictable/Person.py index 916d7344a..010f31d24 100644 --- a/examples/dynamictable/Person.py +++ b/examples/dynamictable/Person.py @@ -3,7 +3,7 @@ class Person: def __init__(self, description = "DESC", name= ""): self.description = description self.name = name - + def getDescription(self): return self.description diff --git a/examples/dynamictable/Professor.py b/examples/dynamictable/Professor.py index 88bd6c206..6e424447c 100644 --- a/examples/dynamictable/Professor.py +++ b/examples/dynamictable/Professor.py @@ -9,9 +9,9 @@ def __init__(self, teachingSchedule=None, **kwargs): self.teachingSchedule = Schedule() else: self.teachingSchedule = teachingSchedule - + def getSchedule(self, daysFilter): return self.teachingSchedule.getDescription(daysFilter) - + def getTeachingSchedule(self): return self.teachingSchedule diff --git a/examples/dynamictable/Schedule.py b/examples/dynamictable/Schedule.py index ff54ca465..01fb658ef 100644 --- a/examples/dynamictable/Schedule.py +++ b/examples/dynamictable/Schedule.py @@ -9,7 +9,7 @@ def __init__(self, timeSlots = None): def addTimeSlot(self, timeSlot): self.timeSlots.append(timeSlot) - + def getDescription(self, daysFilter): s = None for timeSlot in self.timeSlots: diff --git a/examples/dynamictable/SchoolCalendarWidget.py b/examples/dynamictable/SchoolCalendarWidget.py index afbbdf777..c3269c96c 100644 --- a/examples/dynamictable/SchoolCalendarWidget.py +++ b/examples/dynamictable/SchoolCalendarWidget.py @@ -14,13 +14,13 @@ def __init__(self, owner): self.lastStartRow = -1 self.lastMaxRows = -1 self.lastPeople = [] - + def updateRowData(self, startRow, maxRows, acceptor): if startRow == self.lastStartRow: if maxRows == self.lastMaxRows: self.pushResults(acceptor, startRow, self.lastPeople) return - + handler = CalendarProviderHandler(self, acceptor, startRow, maxRows) self.calService.getPeople(startRow, maxRows, handler) @@ -37,24 +37,24 @@ def __init__(self, owner, acceptor, startRow, maxRows): self.acceptor = acceptor self.startRow = startRow self.maxRows = maxRows - + def onRemoteResponse(self, response, requestInfo): people = response - + self.owner.lastStartRow = self.startRow self.owner.lastMaxRows = self.maxRows self.owner.lastPeople = people self.owner.pushResults(self.acceptor, self.startRow, people) - + def onRemoteError(self, code, message, request): self.acceptor.failed(message) - + class SchoolCalendarWidget(Composite): - + def __init__(self, visibleRows): Composite.__init__(self) - + columns = ["Name", "Description", "Schedule"] styles = ["name", "desc", "sched"] self.calProvider = CalendarProvider(self) @@ -63,10 +63,10 @@ def __init__(self, visibleRows): self.dynaTable = DynaTableWidget(self.calProvider, columns, styles, visibleRows) self.initWidget(self.dynaTable) - + def getDayIncluded(self, day): return self.daysFilter[day] - + def onLoad(self): self.dynaTable.refresh() @@ -75,7 +75,7 @@ def setDayIncluded(self, day, included): return self.daysFilter[day] = included - + if not self.pendingRefresh: self.pendingRefresh = True DeferredCommand.add(self) diff --git a/examples/dynamictable/Student.py b/examples/dynamictable/Student.py index e833fed1b..f9217ca43 100644 --- a/examples/dynamictable/Student.py +++ b/examples/dynamictable/Student.py @@ -12,6 +12,6 @@ def __init__(self, classSchedule=None, **kwargs): def getSchedule(self, daysFilter): return self.classSchedule.getDescription(daysFilter) - + def getClassSchedule(self): return self.classSchedule diff --git a/examples/dynamictable/TimeSlot.py b/examples/dynamictable/TimeSlot.py index e3d26ee54..36ec631e3 100644 --- a/examples/dynamictable/TimeSlot.py +++ b/examples/dynamictable/TimeSlot.py @@ -6,7 +6,7 @@ def __init__(self, dayOfWeek, startMinutes, endMinutes): self.dayOfWeek = dayOfWeek self.startMinutes = startMinutes self.endMinutes = endMinutes - + def compareTo(self, other): if self.dayOfWeek < other.dayOfWeek: return -1 @@ -24,7 +24,7 @@ def getDayOfWeek(self): def getDescription(self): return self.DAYS[self.dayOfWeek] + " " + self.getHrsMins(self.startMinutes) + "-" + self.getHrsMins(self.endMinutes) - + def getHrsMins(self, mins): hrs = math.floor(mins / 60) if hrs > 12: diff --git a/examples/employeeadmin/ApplicationConstants.py b/examples/employeeadmin/ApplicationConstants.py index 9151dd0aa..02127a1bf 100644 --- a/examples/employeeadmin/ApplicationConstants.py +++ b/examples/employeeadmin/ApplicationConstants.py @@ -12,8 +12,8 @@ DEPT_QC = 'Quality Control' DeptList = [ DEPT_NONE_SELECTED, - DEPT_ACCT, - DEPT_SALES, + DEPT_ACCT, + DEPT_SALES, DEPT_PLANT ] @@ -34,11 +34,11 @@ ROLE_RETURNS = 'Returns' RoleList = [ ROLE_NONE_SELECTED, - ROLE_ADMIN, - ROLE_ACCT_PAY, - ROLE_ACCT_RCV, - ROLE_EMP_BENEFITS, - ROLE_GEN_LEDGER, + ROLE_ADMIN, + ROLE_ACCT_PAY, + ROLE_ACCT_RCV, + ROLE_EMP_BENEFITS, + ROLE_GEN_LEDGER, ROLE_PAYROLL, ROLE_INVENTORY, ROLE_PRODUCTION, diff --git a/examples/employeeadmin/EmployeeAdmin.py b/examples/employeeadmin/EmployeeAdmin.py index 7dd9395b1..a463d3565 100644 --- a/examples/employeeadmin/EmployeeAdmin.py +++ b/examples/employeeadmin/EmployeeAdmin.py @@ -23,21 +23,21 @@ import controller, components class AppFacade(Facade): - + def __init__(self): self.initializeFacade() self.initializeController() self.registerCommand(Command.STARTUP, controller.StartupCommand) self.registerCommand(Command.DELETE_USER, controller.DeleteUserCommand) self.registerCommand(Command.ADD_ROLE_RESULT, controller.AddRoleResultCommand) - + @staticmethod def getInstance(): return AppFacade() if __name__ == '__main__': - + pyjd.setup("./public/EmployeeAdmin.html") app = AppFacade.getInstance() pyjsApp = components.PyJsApp() diff --git a/examples/employeeadmin/Grid.py b/examples/employeeadmin/Grid.py index 8f8ed6a4f..0faf92bff 100644 --- a/examples/employeeadmin/Grid.py +++ b/examples/employeeadmin/Grid.py @@ -52,4 +52,4 @@ def styleRow(self, row, selected): self.getRowFormatter().addStyleName(row, "user-SelectedRow") else: self.getRowFormatter().removeStyleName(row, "user-SelectedRow") - + diff --git a/examples/employeeadmin/components.py b/examples/employeeadmin/components.py index 5a48f3b3d..f45640f42 100644 --- a/examples/employeeadmin/components.py +++ b/examples/employeeadmin/components.py @@ -22,18 +22,18 @@ import ApplicationConstants class PyJsApp(object): - + appFrame = None - + def __init__(self): self.appFrame = AppFrame() class AppFrame(object): - + userForm = None userList = None rolePanel = None - + def __init__(self): self.panel = DockPanel() self.userList = UserList(self) @@ -49,15 +49,15 @@ def Show(self): pass class RolePanel(AbsolutePanel): - + user = None selectedRole = None - + roleList = None roleCombo = None addBtn = None removeBtn = None - + def __init__(self,parent): AbsolutePanel.__init__(self) @@ -97,13 +97,13 @@ def updateRoleList(self,items): self.roleList.addItem(item) #self.roleList.addItem('       ') #self.roleList.addItem('- - - - - - - -') - + def updateRoleCombo(self,choices, default_): self.roleCombo.clear() for choice in choices: self.roleCombo.addItem(choice) self.roleCombo.selectValue(default_) - + def onComboChange(self, sender, keyCode=None, modifiers=None): selected = self.roleCombo.getSelectedItemText() if not selected \ @@ -116,7 +116,7 @@ def onComboChange(self, sender, keyCode=None, modifiers=None): self.selectedRole=selected[0] self.removeBtn.setEnabled(False) self.roleList.setItemTextSelection(None) - + def onListChange(self, sender): selected = self.roleList.getSelectedItemText() if selected: @@ -127,7 +127,7 @@ def onListChange(self, sender): self.selectedRole=None self.addBtn.setEnabled(False) self.roleCombo.setItemTextSelection(None) - + def onClick(self, sender): pass @@ -144,14 +144,14 @@ def onKeyPress(self, sender, keyCode, modifiers): pass class UserList(AbsolutePanel): - + userGrid = None newBtn = None deleteBtn = None - + users = None selectedUser = None - + def __init__(self,parent): AbsolutePanel.__init__(self) self.userGrid = Grid() @@ -175,9 +175,9 @@ def __init__(self,parent): self.add(self.userGrid) self.add(self.newBtn) self.add(self.deleteBtn) - + return - + def updateUserGrid(self, users): self.userGrid.clearGrid() self.users = users @@ -188,7 +188,7 @@ def updateUserGrid(self, users): self.userGrid.setCellValue(i, 3, users[i].email) self.userGrid.setCellValue(i, 4, users[i].department) self.userGrid.setCellValue(i, 5, users[i].password) - + def onCellClicked(self, sender, row, col): try: if row > 0 and row <= len(self.users): @@ -201,19 +201,19 @@ def onCellClicked(self, sender, row, col): self.deleteBtn.setEnabled(False) except IndexError: pass - + def deSelect(self): self.userGrid.selectRow(-1) - + class UserForm(AbsolutePanel): - + MODE_ADD = "modeAdd"; MODE_EDIT = "modeEdit"; - + user = None mode = None - + usernameInput = None firstInput = None lastInput = None @@ -223,7 +223,7 @@ class UserForm(AbsolutePanel): departmentCombo = None addBtn = None cancelBtn = None - + def __init__(self,parent): AbsolutePanel.__init__(self) ftable = FlexTable() @@ -325,20 +325,20 @@ def updateDepartmentCombo(self,choices, default_): for choice in choices: self.departmentCombo.addItem(choice) self.departmentCombo.selectValue(default_) - + def updateMode(self, mode): self.mode = mode if self.mode == self.MODE_ADD: self.addBtn.setText("Add User") else: self.addBtn.setText("Update User") - + def checkValid(self, evt=None): if self.enableSubmit(self.usernameInput.getText(),self.passwordInput.getText(),self.confirmInput.getText(), self.departmentCombo.getSelectedItemText(True)): self.addBtn.setEnabled(True) else: self.addBtn.setEnabled(False) - + def enableSubmit(self, u, p, c, d): return (len(u) > 0 and len(p) >0 and p == c and len(d) > 0) diff --git a/examples/employeeadmin/controller.py b/examples/employeeadmin/controller.py index 6bdc4cbb3..95d17cae7 100644 --- a/examples/employeeadmin/controller.py +++ b/examples/employeeadmin/controller.py @@ -1,5 +1,5 @@ """ -PureMVC Python Demo - wxPython Employee Admin +PureMVC Python Demo - wxPython Employee Admin By Toby de Havilland Copyright(c) 2007-08 Toby de Havilland, Some rights reserved. Addapted for pyjamas: Kees Bos @@ -14,7 +14,7 @@ def execute(self,note): facade = self.facade facade.registerProxy(model.UserProxy()) facade.registerProxy(model.RoleProxy()) - + mainPanel = note.getBody() facade.registerMediator(view.DialogMediator(mainPanel)) facade.registerMediator(view.UserFormMediator(mainPanel.userForm)) @@ -33,6 +33,6 @@ def execute(self,note): facade = self.facade userProxy = facade.retrieveProxy(model.UserProxy.NAME) roleProxy = facade.retrieveProxy(model.RoleProxy.NAME) - userProxy.deleteItem(user) + userProxy.deleteItem(user) roleProxy.deleteItem(user) facade.sendNotification(Notification.USER_DELETED) diff --git a/examples/employeeadmin/model.py b/examples/employeeadmin/model.py index 15ba04852..4613ead1a 100644 --- a/examples/employeeadmin/model.py +++ b/examples/employeeadmin/model.py @@ -1,5 +1,5 @@ """ -PureMVC Python Demo - wxPython Employee Admin +PureMVC Python Demo - wxPython Employee Admin By Toby de Havilland Copyright(c) 2007-08 Toby de Havilland, Some rights reserved. Addapted for pyjamas: Kees Bos @@ -11,33 +11,33 @@ from ApplicationConstants import Command, Notification class UserProxy(Proxy): - + NAME = "UserProxy" def __init__(self): super(UserProxy, self).__init__(UserProxy.NAME, []) self.data = [] self.addItem(vo.UserVO('lstooge', - 'Larry', - 'Stooge', - "larry@stooges.com", + 'Larry', + 'Stooge', + "larry@stooges.com", 'ijk456', ApplicationConstants.DEPT_ACCT)) self.addItem(vo.UserVO('cstooge', - 'Curly', - 'Stooge', - "curly@stooges.com", + 'Curly', + 'Stooge', + "curly@stooges.com", 'xyz987', ApplicationConstants.DEPT_SALES)) self.addItem(vo.UserVO('mstooge', - 'Moe', - 'Stooge', - "moe@stooges.com", + 'Moe', + 'Stooge', + "moe@stooges.com", 'abc123', ApplicationConstants.DEPT_PLANT)) def getUsers(self): return self.data - + def addItem(self, item): self.data.append(item) @@ -59,14 +59,14 @@ class RoleProxy(Proxy): def __init__(self): super(RoleProxy, self).__init__(RoleProxy.NAME, []) self.data = [] - self.addItem(vo.RoleVO('lstooge', + self.addItem(vo.RoleVO('lstooge', [ApplicationConstants.ROLE_PAYROLL, ApplicationConstants.ROLE_EMP_BENEFITS])) - self.addItem(vo.RoleVO('cstooge', + self.addItem(vo.RoleVO('cstooge', [ApplicationConstants.ROLE_ACCT_PAY, ApplicationConstants.ROLE_ACCT_RCV, ApplicationConstants.ROLE_GEN_LEDGER])) - self.addItem(vo.RoleVO('mstooge', + self.addItem(vo.RoleVO('mstooge', [ApplicationConstants.ROLE_INVENTORY, ApplicationConstants.ROLE_PRODUCTION, ApplicationConstants.ROLE_SALES, diff --git a/examples/employeeadmin/view.py b/examples/employeeadmin/view.py index 706f937b7..f1dafe804 100644 --- a/examples/employeeadmin/view.py +++ b/examples/employeeadmin/view.py @@ -1,5 +1,5 @@ """ -PureMVC Python Demo - wxPython Employee Admin +PureMVC Python Demo - wxPython Employee Admin By Toby de Havilland Copyright(c) 2007-08 Toby de Havilland, Some rights reserved. Addapted for pyjamas: Kees Bos @@ -14,9 +14,9 @@ from pyjamas.Window import alert class DialogMediator(Mediator): - + NAME = 'DialogMediator' - + def __init__(self, viewComponent): super(DialogMediator, self).__init__(DialogMediator.NAME, viewComponent) self.viewComponent.mediator = self @@ -35,21 +35,21 @@ def handleNotification(self, note): raise class UserFormMediator(Mediator): - + NAME = 'UserFormMediator' - + userProxy = None - + def __init__(self, viewComponent): super(UserFormMediator, self).__init__(UserFormMediator.NAME, viewComponent) self.viewComponent.mediator = self self.viewComponent.addBtn.addClickListener(self.onAdd) self.viewComponent.cancelBtn.addClickListener(self.onCancel) - + self.userProxy = self.facade.retrieveProxy(model.UserProxy.NAME) - self.viewComponent.updateDepartmentCombo(ApplicationConstants.DeptList, + self.viewComponent.updateDepartmentCombo(ApplicationConstants.DeptList, ApplicationConstants.DEPT_NONE_SELECTED) - + def listNotificationInterests(self): return [ Notification.NEW_USER, @@ -57,18 +57,18 @@ def listNotificationInterests(self): Notification.USER_SELECTED ] - def handleNotification(self, note): + def handleNotification(self, note): try: noteName = note.getName() if noteName == Notification.NEW_USER: self.viewComponent.clearForm() self.viewComponent.updateMode(self.viewComponent.MODE_ADD) self.viewComponent.firstInput.setFocus(True) - + if noteName == Notification.USER_DELETED: self.viewComponent.user = None self.viewComponent.clearForm() - + if noteName == Notification.USER_SELECTED: user = note.getBody() if not user: @@ -78,7 +78,7 @@ def handleNotification(self, note): self.viewComponent.updateMode(self.viewComponent.MODE_EDIT) except: raise - + def onAdd(self, evnt): if self.viewComponent.mode == self.viewComponent.MODE_ADD: self.addUser() @@ -88,10 +88,10 @@ def onAdd(self, evnt): def addUser(self): l = self.viewComponent.departmentCombo.getSelectedItemText(True) l = l and l[0] or None - user = vo.UserVO(self.viewComponent.usernameInput.getText(), - self.viewComponent.firstInput.getText(), - self.viewComponent.lastInput.getText(), - self.viewComponent.emailInput.getText(), + user = vo.UserVO(self.viewComponent.usernameInput.getText(), + self.viewComponent.firstInput.getText(), + self.viewComponent.lastInput.getText(), + self.viewComponent.emailInput.getText(), self.viewComponent.passwordInput.getText(), l) self.viewComponent.user = user @@ -102,10 +102,10 @@ def addUser(self): def updateUser(self): l = self.viewComponent.departmentCombo.getSelectedItemText(True) l = l and l[0] or None - user = vo.UserVO(self.viewComponent.usernameInput.getText(), - self.viewComponent.firstInput.getText(), - self.viewComponent.lastInput.getText(), - self.viewComponent.emailInput.getText(), + user = vo.UserVO(self.viewComponent.usernameInput.getText(), + self.viewComponent.firstInput.getText(), + self.viewComponent.lastInput.getText(), + self.viewComponent.emailInput.getText(), self.viewComponent.passwordInput.getText(), l) self.viewComponent.user = user @@ -120,7 +120,7 @@ def onCancel(self, evnt): class UserListMediator(Mediator): NAME = 'UserListMediator' - + userProxy = None def __init__(self, viewComponent): @@ -128,10 +128,10 @@ def __init__(self, viewComponent): self.viewComponent.newBtn.addClickListener(self.onNewUser) self.viewComponent.deleteBtn.addClickListener(self.onDeleteUser) self.viewComponent.userGrid.addTableListener(self.onSelectUser) - + self.userProxy = self.facade.retrieveProxy(model.UserProxy.NAME) self.viewComponent.updateUserGrid(self.userProxy.getUsers()) - + def listNotificationInterests(self): return [ Notification.CANCEL_SELECTED, @@ -147,25 +147,25 @@ def handleNotification(self, note): if noteName == Notification.CANCEL_SELECTED: self.viewComponent.deSelect() self.viewComponent.updateUserGrid(self.userProxy.getUsers()) - + elif noteName == Notification.USER_UPDATED: self.viewComponent.deSelect() self.viewComponent.updateUserGrid(self.userProxy.getUsers()) - + elif noteName == Notification.USER_ADDED: self.viewComponent.deSelect() self.viewComponent.updateUserGrid(self.userProxy.getUsers()) - + elif noteName == Notification.USER_DELETED: self.viewComponent.deSelect() self.viewComponent.updateUserGrid(self.userProxy.getUsers()) except: raise - + def onSelectUser(self, evt): self.sendNotification(Notification.USER_SELECTED, self.viewComponent.selectedUser) - + def onNewUser(self, evnt): self.viewComponent.deSelect() self.sendNotification(Notification.NEW_USER) @@ -180,7 +180,7 @@ def onDeleteUser(self, evnt): class RolePanelMediator(Mediator): NAME = 'RolePanelMediator' - + roleProxy = None def __init__(self, viewComponent): @@ -189,12 +189,12 @@ def __init__(self, viewComponent): self.viewComponent.removeBtn.addClickListener(self.onRemoveRole) self.roleProxy = self.facade.retrieveProxy(model.RoleProxy.NAME) - self.viewComponent.updateRoleCombo(ApplicationConstants.RoleList, + self.viewComponent.updateRoleCombo(ApplicationConstants.RoleList, ApplicationConstants.ROLE_NONE_SELECTED) - + def getRolePanel(self): return viewComponent - + def onAddRole(self, evnt): self.roleProxy.addRoleToUser(self.viewComponent.user, self.viewComponent.selectedRole) @@ -213,9 +213,9 @@ def listNotificationInterests(self): Command.ADD_ROLE_RESULT, ] - def handleNotification(self, note): + def handleNotification(self, note): try: - noteName = note.getName() + noteName = note.getName() if noteName == Notification.NEW_USER: self.viewComponent.clearForm() diff --git a/examples/employeeadmin/vo.py b/examples/employeeadmin/vo.py index ccb76e092..5b324cc21 100644 --- a/examples/employeeadmin/vo.py +++ b/examples/employeeadmin/vo.py @@ -1,5 +1,5 @@ """ -PureMVC Python Demo - wxPython Employee Admin +PureMVC Python Demo - wxPython Employee Admin By Toby de Havilland Copyright(c) 2007-08 Toby de Havilland, Some rights reserved. Addapted for pyjamas: Kees Bos @@ -8,9 +8,9 @@ class RoleVO(object): username = None roles = [] - + def __init__(self, username=None,roles=None): - if username: + if username: self.username = username if roles: self.roles = roles @@ -22,7 +22,7 @@ class UserVO(object): email = None password = None department = [] - + def __init__(self,uname=None,fname=None,lname=None,email=None,password=None,department = None): if uname: self.username = uname @@ -32,7 +32,7 @@ def __init__(self,uname=None,fname=None,lname=None,email=None,password=None,depa self.lname = lname if email: self.email = email - if password: + if password: self.password = password if department: self.department = department diff --git a/examples/flowpanel/FlowPanel.py b/examples/flowpanel/FlowPanel.py index 5f292cd3c..e77690006 100644 --- a/examples/flowpanel/FlowPanel.py +++ b/examples/flowpanel/FlowPanel.py @@ -22,13 +22,13 @@ class FlowPanelDemo: IE, excluding IE8, doesn't support inline-blocks, so we have to use a CSS hack (see http://blog.mozilla.com/webdev/2009/02/20/cross-browser-inline-block/ for more on the hack) However, we use spans instead of divs for the Label by providing an 'element' argument.""" - + def __init__(self): self.root = RootPanel() #Flow panel taking up 70% of the page. CSS centers it. self.flow = FlowPanel(Width="70%", StyleName='flow-panel') - - + + for x in range(0, 10): self.panel = VerticalPanel() #Label each image with its number in the sequence diff --git a/examples/gcharttestapp/GChartExample00.py b/examples/gcharttestapp/GChartExample00.py index c975df1c9..d4470e3f4 100644 --- a/examples/gcharttestapp/GChartExample00.py +++ b/examples/gcharttestapp/GChartExample00.py @@ -15,6 +15,6 @@ def __init__(self): self.getCurve().setLegendLabel("x2") self.getXAxis().setAxisLabel("x") self.getYAxis().setAxisLabel("x2") - + diff --git a/examples/gcharttestapp/GChartExample01.py b/examples/gcharttestapp/GChartExample01.py index 18e724c3b..21bd5d444 100644 --- a/examples/gcharttestapp/GChartExample01.py +++ b/examples/gcharttestapp/GChartExample01.py @@ -22,6 +22,6 @@ def __init__(self): self.getXAxis().setHasGridlines(True) self.getYAxis().setAxisLabel("x2") self.getYAxis().setHasGridlines(True) - + diff --git a/examples/gcharttestapp/GChartExample02.py b/examples/gcharttestapp/GChartExample02.py index 97cbaa5bb..0a65376ba 100644 --- a/examples/gcharttestapp/GChartExample02.py +++ b/examples/gcharttestapp/GChartExample02.py @@ -29,7 +29,7 @@ def __init__(self): self.updateButton = Button("Generate New Simulated Revenues") - + self.setChartSize(WIDTH, HEIGHT) self.setChartTitle("" + "Simulated Quarterly Revenues" + @@ -55,33 +55,33 @@ def __init__(self): self.getCurve().getPoint().setAnnotationText(barLabels[iCurve]) self.getCurve().getPoint().setAnnotationLocation( AnnotationLocation.NORTH) - - - + + + for i in range(len(groupLabels)): # formula centers tick-label horizontally on each group self.getXAxis().addTick( len(barLabels)/2. + i*(len(barLabels)+1), groupLabels[i]) - + self.getXAxis().setTickLabelFontSize(20.0) self.getXAxis().setTickLabelThickness(40.0) self.getXAxis().setTickLength(6.0); # small tick-like gap... self.getXAxis().setTickThickness(0); # but with invisible ticks self.getXAxis().setAxisMin(0); # keeps first bar on chart - + self.getYAxis().setAxisMin(0); # Based on sim revenue range self.getYAxis().setAxisMax(MAX_REVENUE); # of 0 to MAX_REVENUE. self.getYAxis().setTickCount(11) self.getYAxis().setHasGridlines(True) self.getYAxis().setTickLabelFormat("$#,###") - + def onClick(self, event): for iCurve in range(self.getNCurves()): for iPoint in range(self.getCurve(iCurve).getNPoints()): self.getCurve(iCurve).getPoint(iPoint).setY(rnd()*MAX_REVENUE) - + self.update() #self.updateButton.setFocus(True) diff --git a/examples/gcharttestapp/GChartExample03.py b/examples/gcharttestapp/GChartExample03.py index 9a81b5f0e..e430d30cb 100644 --- a/examples/gcharttestapp/GChartExample03.py +++ b/examples/gcharttestapp/GChartExample03.py @@ -28,7 +28,7 @@ def __init__(self): self.getCurve().getSymbol().setModelWidth(0.5) for i in range(10): self.getCurve().addPoint(i,i*10) - + if do_axis2: self.addCurve() self.getCurve().setLegendLabel("x2") @@ -40,11 +40,11 @@ def __init__(self): self.getCurve().getSymbol().setBackgroundColor("navy") self.getCurve().getSymbol().setFillThickness(2) self.getCurve().getSymbol().setFillSpacing(5) - + for i in range(self.getCurve(0).getNPoints()): self.getCurve().addPoint(i,i*i) - - + + self.getXAxis().setAxisLabel("x") self.getXAxis().setHasGridlines(True) self.getXAxis().setTickThickness(0); # hide tick marks... @@ -59,6 +59,6 @@ def __init__(self): self.getY2Axis().setHasGridlines(True) # last bar 'sticks out' over right edge, so extend 'grid' right: self.getY2Axis().setTickLength(15) - + diff --git a/examples/gcharttestapp/GChartExample04.py b/examples/gcharttestapp/GChartExample04.py index 335b12241..8e3d7ac15 100644 --- a/examples/gcharttestapp/GChartExample04.py +++ b/examples/gcharttestapp/GChartExample04.py @@ -26,11 +26,11 @@ def __init__(self): self.getCurve().getSymbol().setBorderColor("black") self.getCurve().getSymbol().setWidth(9) self.getCurve().getSymbol().setHeight(9) - + # add (log10-transformed) powers of 2 from 1/4 to 8 for i in range(-2, 4): self.getCurve().addPoint(i,log10(math.pow(2,i))) - + # GChart's "=10^" NumberFormat prefix inverts the log10 # transform self.getYAxis().setTickLabelFormat("=10^#.##") @@ -41,14 +41,14 @@ def __init__(self): for y in range(2, 11): self.getYAxis().addTick(log10(x*y)) x *= 10 - + self.getXAxis().setAxisLabel("x") self.getXAxis().setHasGridlines(True) self.getXAxis().setTickCount(6) - + self.getYAxis().setAxisLabel("2x") self.getYAxis().setHasGridlines(True) - - + + diff --git a/examples/gcharttestapp/GChartExample07.py b/examples/gcharttestapp/GChartExample07.py index b33d1275c..73d0faf44 100644 --- a/examples/gcharttestapp/GChartExample07.py +++ b/examples/gcharttestapp/GChartExample07.py @@ -21,7 +21,7 @@ def __init__(self): pieMarketShare = [0.65,0.20,0.10,0.05] pieTypes = ["Apple", "Cherry", "Pecan", "Bannana"] pieColors = ["green", "red", "maroon", "yellow"] - + self.setChartSize(300, 200) self.setChartTitle("

2008 Sales by Pie Flavor" + "
(Puny Pies, Inc.)

") @@ -55,8 +55,8 @@ def __init__(self): self.getCurve().getPoint().setAnnotationText(pieTypes[i]) self.getCurve().getPoint().setAnnotationLocation( AnnotationLocation.OUTSIDE_PIE_ARC) - - - + + + diff --git a/examples/gcharttestapp/GChartExample14.py b/examples/gcharttestapp/GChartExample14.py index 55a11e159..9a509e277 100644 --- a/examples/gcharttestapp/GChartExample14.py +++ b/examples/gcharttestapp/GChartExample14.py @@ -44,7 +44,7 @@ def __init__(self, gchart, iCurve, phaseShift, n): self.iCurve = iCurve self.phaseShift = phaseShift self.n = n - + def execute(self): for iC in range(self.iCurve, self.iCurve+self.n): if self.gchart.getNCurves() <= self.iCurve: @@ -67,47 +67,47 @@ def execute(self): self.gchart.getCurve(0).getSymbol().getHeight()) self.gchart.getCurve().getSymbol().setWidth( self.gchart.getCurve(0).getSymbol().getWidth()) - + for i in range(0, PERIOD, DELTA_TIME): y = math.sin((2*math.pi*(iC*PERIOD+i+self.phaseShift))/PERIOD) if self.gchart.getCurve(iC).getNPoints()*DELTA_TIME <= i: self.gchart.getCurve(iC).addPoint(iC*PERIOD+i+self.phaseShift, y) else: self.gchart.getCurve(iC).getPoint(i/DELTA_TIME).setY(y) - - - + + + self.gchart.update() - - + + class GChartExample14 (GChart): def __init__(self): GChart.__init__(self) - + self.phase = 0 self.btn = Button("Update", self) self.setChartFootnotes(self.btn) - + self.setChartSize(1000,100) self.setChartTitle("Sine vs Time") self.setPadding("2px") - + self.getXAxis().setAxisLabel("Time (seconds)") self.getXAxis().setHasGridlines(True) self.getXAxis().setTickCount(6) self.getXAxis().setTickLabelFormat("#.##") self.getXAxis().setAxisMin(0) self.getXAxis().setAxisMax(PERIOD*N_PERIODS) - + self.getYAxis().setHasGridlines(True) self.getYAxis().setTickCount(5) self.getYAxis().setAxisMin(-1) self.getYAxis().setAxisMax(1) self.getYAxis().setTickLabelThickness(10) - + self.addCurve() self.getCurve().getSymbol().setSymbolType(SymbolType.VBAR_BASELINE_CENTER) self.getCurve().getSymbol().setBorderWidth(0) @@ -116,13 +116,13 @@ def __init__(self): self.getCurve().getSymbol().setFillThickness(0) self.getCurve().getSymbol().setHeight(1) self.getCurve().getSymbol().setWidth(1) - + for i in range(N_PERIODS): DeferredCommand.add(IncrementalUpdate(self, i, 0, 1)) - + # for int phaseShift=0; phaseShift < N_PERIODS*PERIOD; phaseShift+=DELTA_PHASE) # DeferredCommand.addCommand(IncrementalUpdate(this,0, phaseShift, N_PERIODS)) - + def onClick(self, event): self.phase += DELTA_PHASE for i in range(N_PERIODS): diff --git a/examples/gcharttestapp/GChartExample20.py b/examples/gcharttestapp/GChartExample20.py index d0c9629ae..b73a37a75 100644 --- a/examples/gcharttestapp/GChartExample20.py +++ b/examples/gcharttestapp/GChartExample20.py @@ -227,7 +227,7 @@ def copyFormPropertiesIntoChart(self, p): def getColorSpec(self, backgroundColor, borderColor): for i in range(self.chart.colorSelector.getNObjects()): cs = self.chart.colorSelector.getObject(i) - if (backgroundColor == cs.backgroundColor and + if (backgroundColor == cs.backgroundColor and borderColor == cs.borderColor): return cs diff --git a/examples/gcharttestapp/GChartExample21.py b/examples/gcharttestapp/GChartExample21.py index ab7a96052..ca4454d55 100644 --- a/examples/gcharttestapp/GChartExample21.py +++ b/examples/gcharttestapp/GChartExample21.py @@ -49,7 +49,7 @@ def __init__(self, chart): self.add(self.incrementY) self.add(self.coordinates) self.add(self.decrementY) - + def onClick(self, sender): if sender == self.incrementY: self.chart.getTouchedPoint().setY( @@ -58,18 +58,18 @@ def onClick(self, sender): self.chart.getTouchedPoint().setY( self.chart.getTouchedPoint().getY() - 1) self.chart.update() - + # The 2 HoverUpdateable interface methods: def hoverCleanup(self, hoveredAwayFrom): pass - + def hoverUpdate(self, hoveredOver): # update (x,y) display when they click point self.coordinates.setHTML(hoveredOver.getHovertext()) - + class GChartExample21(GChart): - + def __init__(self): GChart.__init__(self) self.setChartSize(300, 300) @@ -92,7 +92,7 @@ def __init__(self): self.getCurve().getSymbol().setHoverYShift(-30) # 3px, external point selection border self.getCurve().getSymbol().setHoverSelectionBorderWidth(-3) - + # configure curve as a baseline-based bar chart self.getCurve().getSymbol().setSymbolType(SymbolType.VBAR_BASELINE_EAST) self.getCurve().getSymbol().setModelWidth(1) diff --git a/examples/gcharttestapp/GChartExample24.py b/examples/gcharttestapp/GChartExample24.py index 98c1c4314..2b4cc880f 100644 --- a/examples/gcharttestapp/GChartExample24.py +++ b/examples/gcharttestapp/GChartExample24.py @@ -130,34 +130,34 @@ def __init__(self, chart, **kwargs): "Zoom out (shrinks plot area so it fits in selected region)") self.add(self.bzoomIn) self.add(self.bzoomOut) - + def onClick(self, sender): if sender == self.bzoomIn: self.chart.zoomIn() else: self.chart.zoomOut() - + def hoverCleanup(self, hoveredAwayFrom): pass - + def hoverUpdate(self, hoveredOver): pass - - + + MIN_SELECTION_FRACTION_X = 0.1 MIN_SELECTION_FRACTION_Y = 0.1 N_POINTS = 100 - + class GChartExample24(GChart): - + def updateCursor(self): dx = self.p2.x - self.p1.x dy = self.p2.y - self.p1.y - if (not self.moving and + if (not self.moving and abs(dx) >= MIN_SELECTION_FRACTION_X* - (self.getXAxis().getAxisMax()- self.getXAxis().getAxisMin()) - and abs(dy) >= MIN_SELECTION_FRACTION_Y* + (self.getXAxis().getAxisMax()- self.getXAxis().getAxisMin()) + and abs(dy) >= MIN_SELECTION_FRACTION_Y* (self.getYAxis().getAxisMax()-self.getYAxis().getAxisMin())): self.getCurve(self.SELECTION_CURVE).setVisible(True) @@ -169,11 +169,11 @@ def updateCursor(self): self.getCurve(self.SELECTION_CURVE).getSymbol().setModelHeight(abs(dy)) self.getCurve(self.SELECTION_CURVE).getPoint(0).setX((self.p1.x + self.p2.x)/2) self.getCurve(self.SELECTION_CURVE).getPoint(0).setY((self.p1.y + self.p2.y)/2) - + elif self.moving: if self.getCurve(self.SELECTION_CURVE).isVisible(): self.getCurve(self.SELECTION_CURVE).setVisible(False) - + xMin = self.getXAxis().getAxisMin() - dx xMax = self.getXAxis().getAxisMax() - dx yMin = self.getYAxis().getAxisMin() - dy @@ -182,13 +182,13 @@ def updateCursor(self): self.getXAxis().setAxisMax(xMax) self.getYAxis().setAxisMin(yMin) self.getYAxis().setAxisMax(yMax) - - - + + + self.update() - - - + + + def __init__(self): GChart.__init__(self) @@ -204,10 +204,10 @@ def __init__(self): self.zoomIndex = 0 self.zoomController = ZoomController(self) # min plot area fraction zoom selection cursor must capture - + self.initialPlotRegion = Region() self.initialSelectionRegion = Region() - + self.setChartTitle( "Drag to pan; Press Ctrl while drag-selecting a rectangle to zoom") self.setChartSize(500, 150) @@ -220,9 +220,9 @@ def __init__(self): for i in range(N_POINTS): self.getCurve().addPoint(i, math.sin((2* math.pi * i)/N_POINTS)* math.sin(10*(2* math.pi * i)/N_POINTS)) - + self.getCurve().getSymbol().setSymbolType(SymbolType.LINE) - + # will use this curve to create the selection cursor self.addCurve() self.getCurve().addPoint(-Double.MAX_VALUE, -Double.MAX_VALUE) @@ -237,16 +237,16 @@ def __init__(self): # give them some x-panning space self.getXAxis().setAxisMin(0.25*N_POINTS) self.getXAxis().setAxisMax(0.75*N_POINTS) - + self.getYAxis().setTickLabelThickness(50) self.getYAxis().setAxisMin(-0.5) self.getYAxis().setAxisMax(0.5) - + """ self.addClickListener(self) """ self.addMouseListener(self) - + def onMouseEnter(self, sender): pass @@ -262,19 +262,19 @@ def onMouseUp(self, sender, x, y): self.updateCursor() self.selecting = False self.moving = False - - + + def onMouseWheel(self, sender, x, y): event = DOM.eventGetCurrentEvent() DOM.eventPreventDefault(event) if self.getCurve(self.SELECTION_CURVE).isVisible(): if event.isNorth(): self.zoomIn() - + elif event.isSouth(): self.zoomOut() - - + + def onMouseDown(self, sender, x, y): """ * Most browsers, by default, support the ability to @@ -289,12 +289,12 @@ def onMouseDown(self, sender, x, y): self.altPressed = DOM.eventGetAltKey(event) x = self.getXAxis().getMouseCoordinate() y = self.getYAxis().getMouseCoordinate() - if (min(self.p1.x, self.p2.x) <= x and - x <= max(self.p1.x, self.p2.x) and - min(self.p1.y, self.p2.y) <= y and + if (min(self.p1.x, self.p2.x) <= x and + x <= max(self.p1.x, self.p2.x) and + min(self.p1.y, self.p2.y) <= y and y <= max(self.p1.y, self.p2.y)): return; # ignore mouse down inside selection rectangle - + self.p1.x = self.p2.x = x self.p1.y = self.p2.y = y xMin = self.getXAxis().getAxisMin() @@ -311,10 +311,10 @@ def onMouseDown(self, sender, x, y): else: self.selecting = False self.moving = True - + self.updateCursor() - - + + def onMouseMove(self, sender, x, y): event = DOM.eventGetCurrentEvent() DOM.eventPreventDefault(event) @@ -325,9 +325,9 @@ def onMouseMove(self, sender, x, y): if self.moving: self.p1.x = self.p2.x = self.getXAxis().getMouseCoordinate() self.p1.y = self.p2.y = self.getYAxis().getMouseCoordinate() - - - + + + def onClick(self, event): x = self.getXAxis().getMouseCoordinate() y = self.getYAxis().getMouseCoordinate() @@ -338,13 +338,13 @@ def onClick(self, event): self.getYAxis().setAxisMax(.5) self.getCurve(self.SELECTION_CURVE).setVisible(False) self.update() - + elif self.getCurve(self.SELECTION_CURVE).isVisible(): self.p1.x = self.p2.x = x self.p1.y = self.p2.y = y self.getCurve(self.SELECTION_CURVE).setVisible(False) self.update() - + else: xMin = self.getXAxis().getAxisMin() xMax = self.getXAxis().getAxisMax() @@ -358,12 +358,12 @@ def onClick(self, event): self.zoomIndex = 0 self.getCurve(self.SELECTION_CURVE).setVisible(True) self.updateCursor() - + self.moving = self.selecting = False - + def zoomIn(self): - + if -1 == self.zoomIndex: # return to starting (0 index) state self.getXAxis().setAxisMin(self.initialPlotRegion.xMin) @@ -374,7 +374,7 @@ def zoomIn(self): self.p2.x = self.initialSelectionRegion.xMax self.p1.y = self.initialSelectionRegion.yMin self.p2.y = self.initialSelectionRegion.yMax - + else: xMin = self.getXAxis().getAxisMin() xMax = self.getXAxis().getAxisMax() @@ -397,32 +397,32 @@ def zoomIn(self): xMax = (self.p1.x + self.p2.x + dx)/2 yMin = (self.p1.y + self.p2.y - dy)/2 yMax = (self.p1.y + self.p2.y + dy)/2 - - + + pXMin = min(self.p1.x, self.p2.x) pXMax = max(self.p1.x, self.p2.x) pYMin = min(self.p1.y, self.p2.y) pYMax = max(self.p1.y, self.p2.y) - + newPXSize = (pXMax-pXMin)*(pXMax-pXMin)/(xMax - xMin) newPYSize = (pYMax-pYMin)*(pYMax-pYMin)/(yMax - yMin) - + xCenter = (self.p1.x + self.p2.x)/2 yCenter = (self.p1.y + self.p2.y)/2 self.p1.x = xCenter - newPXSize/2 self.p2.x = xCenter + newPXSize/2 self.p1.y = yCenter - newPYSize/2 self.p2.y = yCenter + newPYSize/2 - + self.getXAxis().setAxisMin(pXMin) self.getXAxis().setAxisMax(pXMax) self.getYAxis().setAxisMin(pYMin) self.getYAxis().setAxisMax(pYMax) - - + + self.updateCursor() self.zoomIndex += 1 - + def zoomOut(self): if 1 == self.zoomIndex: # return to starting (0 index) state @@ -434,7 +434,7 @@ def zoomOut(self): self.p2.x = self.initialSelectionRegion.xMax self.p1.y = self.initialSelectionRegion.yMin self.p2.y = self.initialSelectionRegion.yMax - + else: xMin = self.getXAxis().getAxisMin() xMax = self.getXAxis().getAxisMax() @@ -458,15 +458,15 @@ def zoomOut(self): xMax = xCenter + dx/2 yMin = yCenter - dy/2 yMax = yCenter + dy/2 - + pXMin = min(self.p1.x, self.p2.x) pXMax = max(self.p1.x, self.p2.x) pYMin = min(self.p1.y, self.p2.y) pYMax = max(self.p1.y, self.p2.y) - + newXSize = (xMax - xMin)*(xMax - xMin)/(pXMax-pXMin) newYSize = (yMax - yMin)*(yMax - yMin)/(pYMax-pYMin) - + dx = xMax - xMin dy = yMax - yMin xCenter = (self.p1.x + self.p2.x)/2 @@ -475,23 +475,23 @@ def zoomOut(self): self.p2.x = xCenter + dx/2 self.p1.y = yCenter - dy/2 self.p2.y = yCenter + dy/2 - + newXMin = (xMin + xMax - newXSize)/2.0 newXMax = (xMin + xMax + newXSize)/2.0 newYMin = (yMin + yMax - newYSize)/2.0 newYMax = (yMin + yMax + newYSize)/2.0 - + self.getXAxis().setAxisMin(newXMin) self.getXAxis().setAxisMax(newXMax) self.getYAxis().setAxisMin(newYMin) self.getYAxis().setAxisMax(newYMax) - + self.p1.x = xMin self.p2.x = xMax self.p1.y = yMin self.p2.y = yMax - + self.zoomIndex -= 1 self.updateCursor() - + diff --git a/examples/gcharttestapp/GChartTestApp.py b/examples/gcharttestapp/GChartTestApp.py index ed28b4b52..0b2f7eda0 100644 --- a/examples/gcharttestapp/GChartTestApp.py +++ b/examples/gcharttestapp/GChartTestApp.py @@ -11,15 +11,15 @@ from pyjamas.Canvas.GWTCanvas import GWTCanvas -from TestGChart00 import TestGChart00 -from TestGChart01 import TestGChart01 -from TestGChart02 import TestGChart02 +from TestGChart00 import TestGChart00 +from TestGChart01 import TestGChart01 +from TestGChart02 import TestGChart02 -from TestGChart05 import TestGChart05 +from TestGChart05 import TestGChart05 -from GChartExample00 import GChartExample00 +from GChartExample00 import GChartExample00 from GChartExample00a import GChartExample00a -from GChartExample01 import GChartExample01 +from GChartExample01 import GChartExample01 from GChartExample02 import GChartExample02 from GChartExample03 import GChartExample03 from GChartExample04 import GChartExample04 @@ -61,7 +61,7 @@ * the test should go through very quickly. * """ - + """ Linear congruent random number generator. * * Cannot use GWT's Math.random() because, for automated @@ -99,7 +99,7 @@ def rnd(): * HTML/hash code, so you must run the test via the Compile/Browse button. * """ - + from GChartTestAppUtil import getTitle class AddOneChart: @@ -107,13 +107,13 @@ def __init__(self, gchart, needsUpdate=True): #gchart.setOptimizeForMemory(True) self.gchart = gchart self.needsUpdate = needsUpdate - + def execute(self): RootPanel("testappcharts").add(HTML(getTitle(self.gchart))) RootPanel("testappcharts").add(self.gchart) if self.needsUpdate: self.gchart.update() - + @@ -129,10 +129,10 @@ def create(self): def onModuleLoad(): - + # TODO: port http://code.google.com/p/gwt-canvas GChart.setCanvasFactory(GWTCanvasBasedCanvasFactory()) - + # thinking about retiring these tests: # addChart(GChartExample11(0,2,False)) # addChart(GChartExample11(0,3,False)) @@ -145,7 +145,7 @@ def onModuleLoad(): # DeferredCommand.add(Command() { void execute() { # RootPanel.get().add(TestGChart41a()) # }}) - + # To focus on a single test, simply use Eclipse's Source, Toggle comment #addChart(GChartExample00()) #addChart(GChartExample00a()) @@ -197,7 +197,7 @@ def onModuleLoad(): #DeferredCommand.add(Command() { # def execute(self): # RootPanel.get().add(GChartExample25()) - # + # #) # addChart(TestGChart00()) #addChartNoUpdate(TestGChart01(0,0)) @@ -404,12 +404,12 @@ def onModuleLoad(): #RootPanel.get().add(TestGChart58()) #addChart(TestGChart00()) - + RootPanel("loadingMessage").setVisible(False) - - - - + + + + if __name__ == '__main__': onModuleLoad() diff --git a/examples/gcharttestapp/GChartTestAppUtil.py b/examples/gcharttestapp/GChartTestAppUtil.py index 2458dbeab..1d57a0bc9 100644 --- a/examples/gcharttestapp/GChartTestAppUtil.py +++ b/examples/gcharttestapp/GChartTestAppUtil.py @@ -23,7 +23,7 @@ * the test should go through very quickly. * """ - + # convenience method to create a short, class-name-based title def getTitle(obj): result = obj.__class__.__name__ diff --git a/examples/gcharttestapp/TestGChart00.py b/examples/gcharttestapp/TestGChart00.py index 7961c3193..cfdbff264 100644 --- a/examples/gcharttestapp/TestGChart00.py +++ b/examples/gcharttestapp/TestGChart00.py @@ -9,6 +9,6 @@ def __init__(self): GChart.__init__(self, XChartSize=150, YChartSize=150) self.setChartTitle(GChartTestAppUtil.getTitle(self)) self.setChartFootnotes("Check: Consistent with a 'no data' chart (and it doesn't crash).") - + diff --git a/examples/gcharttestapp/TestGChart02.py b/examples/gcharttestapp/TestGChart02.py index 7dc0b8b91..28e75e759 100644 --- a/examples/gcharttestapp/TestGChart02.py +++ b/examples/gcharttestapp/TestGChart02.py @@ -78,7 +78,7 @@ def __init__(self): self.getCurve(i).getSymbol().setHeight(7) self.getCurve(i).getSymbol().setWidth(7) self.getCurve(i).setLegendLabel("%d %s " % (i, symbolNames[i])) - + self.setLegendFontSize(8) self.getXAxis().setTickLabelFontSize(8) self.getXAxis().setHasGridlines(True) @@ -86,7 +86,7 @@ def __init__(self): self.getYAxis().setTickLabelFontSize(8) self.getYAxis().setHasGridlines(True) self.getYAxis().setTickCount(len(symbolTypes)) - - + + diff --git a/examples/gcharttestapp/TestGChart05.py b/examples/gcharttestapp/TestGChart05.py index 43a36eba1..a6ce2f86d 100644 --- a/examples/gcharttestapp/TestGChart05.py +++ b/examples/gcharttestapp/TestGChart05.py @@ -11,13 +11,13 @@ def __init__(self, testCanvas): self.setChartTitle(GChartTestAppUtil.getTitle(self)) self.setClipToPlotArea(True) self.setChartFootnotes("Check: an unclipped point at each corner.
No x-ticks.
Line clipped at plot area limits
Three clipped-off pies visible
Every at-least-partly visible symbol labeled.") - + self.getXAxis().setHasGridlines(True) self.getY2Axis().setHasGridlines(True) self.addCurve() if testCanvas: self.getCurve().getSymbol().setFillSpacing(0) - + self.getCurve().setYAxis(GChartConsts.Y_AXIS) self.getCurve().addPoint(0,-95); # clipped self.getCurve().getPoint().setAnnotationText(self.getCurve().getPoint().getHovertext()) @@ -27,12 +27,12 @@ def __init__(self, testCanvas): self.getCurve().getPoint().setAnnotationText(self.getCurve().getPoint().getHovertext()) self.getCurve().addPoint(0,5); # clipped self.getCurve().getPoint().setAnnotationText(self.getCurve().getPoint().getHovertext()) - + self.getCurve().setLegendLabel("On Y") self.addCurve() if testCanvas: self.getCurve().getSymbol().setFillSpacing(0) - + self.getCurve().setYAxis(GChartConsts.Y2_AXIS) self.getCurve().addPoint(90,-50); # clipped self.getCurve().getPoint().setAnnotationText(self.getCurve().getPoint().getHovertext()) @@ -43,7 +43,7 @@ def __init__(self, testCanvas): self.getCurve().addPoint(90,50); # clipped self.getCurve().getPoint().setAnnotationText(self.getCurve().getPoint().getHovertext()) self.getCurve().setLegendLabel("On Y2") - + # continuous line whose edges self.get clipped off self.addCurve() self.getCurve().setLegendLabel("clipped line") @@ -51,10 +51,10 @@ def __init__(self, testCanvas): self.getCurve().getSymbol().setBorderColor("blue") if testCanvas: self.getCurve().getSymbol().setFillSpacing(0) - + else: self.getCurve().getSymbol().setFillSpacing(10) - + self.getCurve().getSymbol().setFillThickness(3) self.getCurve().setYAxis(GChartConsts.Y_AXIS) # self.getCurve().addPoint(50,-50) @@ -63,12 +63,12 @@ def __init__(self, testCanvas): # self.getCurve().addPoint(50,-50) self.getCurve().addPoint(100,0) self.getCurve().getPoint().setAnnotationText(self.getCurve().getPoint().getHovertext()) - + # this should be entirely visible self.addCurve() if testCanvas: self.getCurve().getSymbol().setFillSpacing(0) - + self.getCurve().setLegendLabel("inside pie") self.getCurve().getSymbol().setSymbolType( SymbolType.PIE_SLICE_HORIZONTAL_SHADING) @@ -78,12 +78,12 @@ def __init__(self, testCanvas): self.getCurve().setYAxis(GChartConsts.Y_AXIS) self.getCurve().addPoint(45,0) self.getCurve().getPoint().setAnnotationText(self.getCurve().getPoint().getHovertext()) - + # this should be entirely clipped. self.addCurve() if testCanvas: self.getCurve().getSymbol().setFillSpacing(0) - + self.getCurve().setLegendLabel("outside right pie") self.getCurve().getSymbol().setSymbolType( SymbolType.PIE_SLICE_HATCHED_SHADING) @@ -97,7 +97,7 @@ def __init__(self, testCanvas): self.addCurve() if testCanvas: self.getCurve().getSymbol().setFillSpacing(0) - + self.getCurve().setLegendLabel("outside bottom pie") self.getCurve().getSymbol().setSymbolType( SymbolType.PIE_SLICE_VERTICAL_SHADING) @@ -107,7 +107,7 @@ def __init__(self, testCanvas): self.getCurve().setYAxis(GChartConsts.Y_AXIS) self.getCurve().addPoint(45,-95) self.getCurve().getPoint().setAnnotationText(self.getCurve().getPoint().getHovertext()) - + self.getXAxis().setAxisLabel("X") self.getXAxis().setTickCount(0) self.getXAxis().setAxisMin(0.) @@ -116,7 +116,7 @@ def __init__(self, testCanvas): self.getYAxis().setAxisMax(0.) self.getY2Axis().setAxisMin(-45.) self.getY2Axis().setAxisMax(45) - - + + diff --git a/examples/getattr/MainTest.py b/examples/getattr/MainTest.py index 430d302c2..2f17a2e9b 100644 --- a/examples/getattr/MainTest.py +++ b/examples/getattr/MainTest.py @@ -30,7 +30,7 @@ def onModuleLoad(self): @staticmethod def printable(text): log(text) - + class StoringObject: def save(self,func): self.func = func diff --git a/examples/gridedit/GridEdit.py b/examples/gridedit/GridEdit.py index 5c58ae30d..50850a580 100644 --- a/examples/gridedit/GridEdit.py +++ b/examples/gridedit/GridEdit.py @@ -14,7 +14,7 @@ class GridEdit: def onModuleLoad(self): - + self.input = TextBox() self.input.setEnabled(False) self.input.addKeyboardListener(self) @@ -28,7 +28,7 @@ def onModuleLoad(self): self.g.setWidth("500px") self.g.setHeight("120px") self.g.addTableListener(self) - + self.initGrid() RootPanel().add(self.input) RootPanel().add(self.g) @@ -46,7 +46,7 @@ def onKeyPress(self, sender, keycode, modifiers): self.input.setEnabled(False) val = self.input.getText() self.set_grid_value(self.row, self.col, val) - + def onCellClicked(self, sender, row, col): self.row = row self.col = col @@ -62,7 +62,7 @@ def set_grid_value(self, row, col, val): self.g.setHTML(row, col, val) def initGrid(self): - + self.values = {} for y in range(5): self.values[y] = {} diff --git a/examples/gridtest/GridTest.py b/examples/gridtest/GridTest.py index c35c62203..510a95dcc 100644 --- a/examples/gridtest/GridTest.py +++ b/examples/gridtest/GridTest.py @@ -19,18 +19,18 @@ def __init__(self): self.page=0 self.min_page=1 self.max_page=10 - + self.addb=Button("Next >", self) self.subb=Button("< Prev", self) self.clearb=Button("Clear", self) - + self.g=Grid() self.g.resize(5, 5) self.g.setWidget(0, 0, HTML("Grid Test")) self.g.setBorderWidth(2) self.g.setCellPadding(4) self.g.setCellSpacing(1) - + self.updatePageDisplay() self.add(self.subb) @@ -48,20 +48,20 @@ def onClick(self, sender): elif sender==self.subb: self.page-=1 self.updatePageDisplay() - + def updatePageDisplay(self): if self.pageself.max_page: self.page=self.max_page total_pages=(self.max_page-self.min_page) + 1 - + self.g.setHTML(0, 4, "page %d of %d" % (self.page, total_pages)) - + if self.page>=self.max_page: self.addb.setEnabled(False) else: self.addb.setEnabled(True) - + if self.page<=self.min_page: self.subb.setEnabled(False) else: diff --git a/examples/gwtcanvas/GradientDemo.py b/examples/gwtcanvas/GradientDemo.py index 0b8ba5c78..2881bcc8a 100644 --- a/examples/gwtcanvas/GradientDemo.py +++ b/examples/gwtcanvas/GradientDemo.py @@ -31,33 +31,33 @@ def __init__(self): layout.add(HTML( "Stroke Gradients currently not working correctly in IE. RadialGradients are not supported in VML. Contributor assistance welcome :).")) Composite.__init__(self, layout) - + """* * Simple Demo of gradient fills and strokes. """ class GradientDemo (SimpleCanvasDemo): - + def __init__(self, theCanvas): SimpleCanvasDemo.__init__(self, theCanvas) self.width = 400 self.height = 400 self.demoName = "Gradients" - - + + def createControls(self): self.controls = GradientDemoControls() - - + + def drawDemo(self): self.canvas.resize(self.width, self.height) - + # DRAW SOME LINEAR GRADIENTS # Demos ported from Mozilla Development Center Canvas Tutorial self.canvas.saveContext() - + # Create gradients lingrad = self.canvas.createLinearGradient(0, 0, 0, 150) lingrad.addColorStop(0.0, Color("#00ABEB")) @@ -68,42 +68,42 @@ def drawDemo(self): lingrad2 = self.canvas.createLinearGradient(0, 50, 0, 95) lingrad2.addColorStop(0.5, Color("#000")) lingrad2.addColorStop(1, Color("rgba(0,0,0,0)")) - + # assign gradients to fill and stroke styles self.canvas.setFillStyle(lingrad) self.canvas.setStrokeStyle(lingrad2) - + # draw shapes self.canvas.fillRect(10, 10, 130, 130) self.canvas.strokeRect(50, 50, 50, 50) - + self.canvas.restoreContext() - + # DRAW SOME RADIAL GRADIENTS # Demos ported from Mozilla Development Center Canvas Tutorial self.canvas.saveContext() self.canvas.translate(150, 150) - + radgrad = self.canvas.createRadialGradient(45, 45, 10, 52, 50, 30) radgrad.addColorStop(0, Color("#A7D30C")) radgrad.addColorStop(0.9, Color("#019F62")) radgrad.addColorStop(1, Color("rgba(1,159,98,0)")) - + radgrad2 = self.canvas.createRadialGradient(105, 105, 20, 112, 120, 50) radgrad2.addColorStop(0, Color("#FF5F98")) radgrad2.addColorStop(0.75, Color("#FF0188")) radgrad2.addColorStop(1, Color("rgba(255,1,136,0)")) - + radgrad3 = self.canvas.createRadialGradient(95, 15, 15, 102, 20, 40) radgrad3.addColorStop(0, Color("#00C9FF")) radgrad3.addColorStop(0.8, Color("#00B5E2")) radgrad3.addColorStop(1, Color("rgba(0,201,255,0)")) - + radgrad4 = self.canvas.createRadialGradient(0, 150, 50, 0, 140, 90) radgrad4.addColorStop(0, Color("#F4F201")) radgrad4.addColorStop(0.8, Color("#E4C700")) radgrad4.addColorStop(1, Color("rgba(228,199,0,0)")) - + # draw shapes self.canvas.setFillStyle(radgrad4) self.canvas.fillRect(0, 0, 150, 150) @@ -113,12 +113,12 @@ def drawDemo(self): self.canvas.fillRect(0, 0, 150, 150) self.canvas.setFillStyle(radgrad) self.canvas.fillRect(0, 0, 150, 150) - + self.canvas.restoreContext() - - + + def stopDemo(self): pass - + diff --git a/examples/gwtcanvas/StaticDemo.py b/examples/gwtcanvas/StaticDemo.py index 49c37c2c1..38965a0e0 100644 --- a/examples/gwtcanvas/StaticDemo.py +++ b/examples/gwtcanvas/StaticDemo.py @@ -36,18 +36,18 @@ def __init__(self): * as well as transformations, and style settings. """ class StaticDemo (SimpleCanvasDemo): - + def __init__(self, theCanvas): SimpleCanvasDemo.__init__(self, theCanvas) self.width = 400 self.height = 400 self.demoName = "Static Scene" - - + + def createControls(self): self.controls = StaticDemoControls() - - + + """ * Test cases derived from javascript test cases by Emil Eklund * and from Mozilla foundation Canvas tutorial. Please note that @@ -55,42 +55,42 @@ def createControls(self): * originally derived from mozilla foundation test cases """ def drawDemo(self): - + self.canvas.resize(self.width, self.height) - + # Changing the coordinate size will implicitly clear the self.canvas # self.canvas.clear() self.canvas.saveContext() - + self.canvas.setLineWidth(1) self.canvas.setFillStyle(Color.GREEN) self.canvas.fillRect(5, 5, 25, 25) self.canvas.setStrokeStyle(Color.RED) self.canvas.strokeRect(20, 20, 25, 25) - + self.canvas.beginPath() - + self.canvas.setLineWidth(1) - + self.canvas.moveTo(1,1) self.canvas.lineTo(80,80) self.canvas.lineTo(100,20) self.canvas.closePath() self.canvas.stroke() - + self.canvas.setStrokeStyle(Color.BLUE) self.canvas.setFillStyle(Color.BLACK) - + self.canvas.beginPath() self.canvas.moveTo(120,50) self.canvas.lineTo(150,70) self.canvas.lineTo(150,50) - + self.canvas.quadraticCurveTo(150, 150, 80, 80) self.canvas.cubicCurveTo(85,25,75,37,75,40) self.canvas.closePath() self.canvas.fill() - + self.canvas.setFont("bold 16px Verdana") self.canvas.fillText("PYJS",20,120) @@ -98,14 +98,14 @@ def drawDemo(self): self.canvas.rect(180,180,80,80) self.canvas.rect(200,200,80,80) self.canvas.stroke() - + self.canvas.beginPath() self.canvas.arc(200, 100, 20, 0, math.pi, False) self.canvas.stroke() - + self.canvas.saveContext() self.canvas.translate(150, 0) - + self.canvas.fillRect(0,0,150,150) self.canvas.setFillStyle(Color.Color("#09F")) self.canvas.fillRect(15,15,120,120) @@ -114,11 +114,11 @@ def drawDemo(self): self.canvas.fillRect(30,30,90,90) self.canvas.fillRect(45,45,60,60) self.canvas.fillRect(60,60,30,30) - + self.canvas.restoreContext() self.canvas.saveContext() self.canvas.translate(10, 140) - + self.canvas.setFillStyle(Color.Color("#FD0")) self.canvas.fillRect(0,0,75,75) self.canvas.setFillStyle(Color.Color("#6C0")) @@ -128,15 +128,15 @@ def drawDemo(self): self.canvas.setFillStyle(Color.Color("#F30")) self.canvas.fillRect(75,75,75,75) self.canvas.setFillStyle(Color.Color("#FFF")) - + self.canvas.setGlobalAlpha(0.2) - + for i in range(7): self.canvas.beginPath() self.canvas.arc(75, 75, 10 + (10 * i), 0, math.pi * 2, False) self.canvas.fill() - - + + self.canvas.saveContext() self.canvas.setGlobalAlpha(0.8) self.canvas.beginPath() @@ -149,43 +149,43 @@ def drawDemo(self): self.canvas.arc(90,65,5,0, math.pi * 2,True); # Right eye self.canvas.stroke() self.canvas.restoreContext() - + self.canvas.restoreContext() - + self.canvas.beginPath() self.canvas.arc(200, 200, 20, 0, math.pi * 2, False) self.canvas.stroke() - + self.canvas.saveContext() self.canvas.setGlobalAlpha(1.0) - + for i in range(6): # Loop through rings (from inside to out) self.canvas.saveContext() self.canvas.setFillStyle(Color.Color((51 * i),(255 - 51 * i),255)) - + for j in range(i*6): # draw individual dots self.canvas.rotate(math.pi * 2 / ( i * 6.)) self.canvas.beginPath() - + self.canvas.rect(0, i * 12.5,5,5) self.canvas.fill() - - + + self.canvas.restoreContext() - - + + self.canvas.restoreContext() - + self.canvas.restoreContext() # self.canvas.clear() - - + + def stopDemo(self): # This demo is not animated so this is a no-op pass - - + + diff --git a/examples/gwtcanvas/SuiteDemo.py b/examples/gwtcanvas/SuiteDemo.py index 4feb194ae..cb99a635c 100644 --- a/examples/gwtcanvas/SuiteDemo.py +++ b/examples/gwtcanvas/SuiteDemo.py @@ -41,7 +41,7 @@ class SuiteDemoControls (Composite): def __init__(self, chart): self.chart = chart self.canvas = chart.canvas - + self.b2 = Button("Compositing", self) self.b3 = Button("Paths & shapes", self) self.b4 = Button("Arcs & circles", self) @@ -55,7 +55,7 @@ def __init__(self, chart): self.b9 = Button("Animations", self) self.b12 = Button("Text", self) self.b13 = Button("Gradients", self) - + hp = HorizontalPanel() vp = VerticalPanel() vp.setHorizontalAlignment(HasAlignment.ALIGN_LEFT) @@ -75,9 +75,9 @@ def __init__(self, chart): vp.add(self.b12) vp.add(self.b13) hp.add(vp) - + Composite.__init__(self, hp) - + def onClick(self, sender): if sender == self.b2: self.onClickCompositing(sender) @@ -109,7 +109,7 @@ def onClick(self, sender): # compositing def onClickCompositing(self, sender): self.chart.run = False - + self.canvas.saveContext() self.canvas.clear() self.canvas.translate(40, 40) @@ -122,11 +122,11 @@ def onClickCompositing(self, sender): self.canvas.setFillStyle(Color.Color("#00f")) self.canvas.fillRect(40, 85, 100, 100) self.canvas.restoreContext() - + # paths / shapes def onClickPaths(self, sender): self.chart.run = False - + self.canvas.saveContext() self.canvas.clear() self.canvas.translate(30, 30) @@ -156,11 +156,11 @@ def onClickPaths(self, sender): self.canvas.rect(165, 25, 100, 100) self.canvas.stroke() self.canvas.restoreContext() - + # arcs / circles def onClickArcs(self, sender): self.chart.run = False - + self.canvas.saveContext() self.canvas.clear() self.canvas.translate(30, 70) @@ -181,9 +181,9 @@ def onClickArcs(self, sender): self.canvas.fill() else: self.canvas.stroke() - - - + + + self.canvas.translate(160, 20) self.canvas.setStrokeStyle(Color.Color("#ff0")) self.canvas.setLineWidth(4) @@ -197,11 +197,11 @@ def onClickArcs(self, sender): self.canvas.arc(90, 65, 5, 0, (math.pi * 2), True) self.canvas.stroke() self.canvas.restoreContext() - + # bezier def onClickBezier(self, sender): self.chart.run = False - + self.canvas.saveContext() self.canvas.clear() self.canvas.translate(30, 70) @@ -228,11 +228,11 @@ def onClickBezier(self, sender): self.canvas.cubicCurveTo(85, 25, 75, 37, 75, 40) self.canvas.fill() self.canvas.restoreContext() - + # colours def onClickColours(self, sender): self.chart.run = False - + self.canvas.saveContext() self.canvas.clear() self.canvas.translate(20, 20) @@ -244,8 +244,8 @@ def onClickColours(self, sender): int(math.floor(255 - 42.5 * j)), 0)) self.canvas.fillRect(j * 25, i * 25, 25, 25) - - + + self.canvas.translate(160, 160) for i in range(6): for j in range(6): @@ -256,14 +256,14 @@ def onClickColours(self, sender): self.canvas.arc(12.5 + j * 25, 12.5 + i * 25, 10, 0, (math.pi * 2), True) self.canvas.stroke() - - + + self.canvas.restoreContext() - + # translating def onClickTranslate(self, sender): self.chart.run = False - + color = [ Color.Color("#fc0"), Color.Color("#0cf"), Color.Color("#cf0") ] self.canvas.saveContext() self.canvas.clear() @@ -276,14 +276,14 @@ def onClickTranslate(self, sender): self.chart.drawSpirograph(2000, 20.0 * (j + 2) / (j + 1), -8.0 * (i + 3) / (i + 1), 10.0) self.canvas.restoreContext() - - + + self.canvas.restoreContext() - + # scaling def onClickScale(self, sender): self.chart.run = False - + self.canvas.saveContext() self.canvas.clear() self.canvas.translate(25, 25) @@ -324,11 +324,11 @@ def onClickScale(self, sender): self.chart.drawSpirograph(2000, 22, 6, 5) self.canvas.restoreContext() self.canvas.restoreContext() - + # rotating def onClickRotate(self, sender): self.chart.run = False - + self.canvas.saveContext() self.canvas.clear() self.canvas.translate(175, 175) @@ -343,15 +343,15 @@ def onClickRotate(self, sender): self.canvas.arc(0, i * 12.5, 5, 0, (math.pi * 2), True) # self.canvas.rect(0,i*12.5,5,5) self.canvas.fill() - + self.canvas.restoreContext() - + self.canvas.restoreContext() - + # lines def onClickLines(self, sender): self.chart.run = False - + self.canvas.saveContext() self.canvas.clear() self.canvas.scale(0.9, 0.9) @@ -364,7 +364,7 @@ def onClickLines(self, sender): self.canvas.moveTo(5 + i * 14, 5) self.canvas.lineTo(5 + i * 14, 140) self.canvas.stroke() - + self.canvas.restoreContext() self.canvas.saveContext() self.canvas.translate(0, 170) @@ -438,22 +438,22 @@ def onClickLines(self, sender): dy = 25.0 else: dy = -25.0 - + self.canvas.lineTo( (math.pow(i, 1.5) * 2.0), 75 + dy) - + self.canvas.stroke() self.canvas.restoreContext() self.canvas.restoreContext() - + # timer def onClickClock(self, sender): self.chart.run = True self.chart.drawClock() - + # transparency def onClickTrans(self, sender): self.chart.run = False - + self.canvas.saveContext() self.canvas.clear() self.canvas.translate(20, 180) @@ -470,8 +470,8 @@ def onClickTrans(self, sender): ((i + 1) / 10.0))) for j in range(4): self.canvas.fillRect(5 + i * 14.0, 5 + j * 37.5, 14, 27.5) - - + + self.canvas.restoreContext() self.canvas.saveContext() self.canvas.translate(180, 20) @@ -490,9 +490,9 @@ def onClickTrans(self, sender): self.canvas.beginPath() self.canvas.arc(75, 75, 10 + (10 * i), 0, (math.pi * 2), True) self.canvas.fill() - + self.canvas.restoreContext() - + # text def onClickText(self, sender): @@ -526,7 +526,7 @@ def onClickText(self, sender): self.canvas.restoreContext() self.canvas.restoreContext() - + def onClickGradients(self, sender): self.chart.run = False @@ -625,7 +625,7 @@ def onClickGradients(self, sender): # Demos copied from GradientsDemo for testing self.canvas.saveContext() self.canvas.translate(150, 150) - + radgrad = self.canvas.createRadialGradient(45, 45, 10, 52, 50, 30) radgrad.addColorStop(0, Color.Color("#A7D30C")) radgrad.addColorStop(0.5, Color.Color("#019F62")) @@ -636,17 +636,17 @@ def onClickGradients(self, sender): radgrad2.addColorStop(0, Color.Color("#FF5F98")) radgrad2.addColorStop(0.75, Color.Color("#FF0188")) radgrad2.addColorStop(1, Color.Color("rgba(255,1,136,0)")) - + radgrad3 = self.canvas.createRadialGradient(95, 15, 15, 102, 20, 40) radgrad3.addColorStop(0, Color.Color("#00C9FF")) radgrad3.addColorStop(0.8, Color.Color("#00B5E2")) radgrad3.addColorStop(1, Color.Color("rgba(0,201,255,0)")) - + radgrad4 = self.canvas.createRadialGradient(0, 150, 50, 0, 140, 90) radgrad4.addColorStop(0, Color.Color("#F4F201")) radgrad4.addColorStop(0.8, Color.Color("#E4C700")) radgrad4.addColorStop(1, Color.Color("rgba(228,199,0,0)")) - + # draw shapes self.canvas.setFillStyle(radgrad4) self.canvas.fillRect(0, 0, 150, 150) @@ -658,39 +658,39 @@ def onClickGradients(self, sender): self.canvas.setFillStyle(radgrad) self.canvas.fillRect(0, 0, 150, 150) - + self.canvas.restoreContext() self.canvas.restoreContext() - - + + """* * Demo showcaseing a range of tests from the Mozilla Canvas Tutorial * and from contributions from Oliver Zoran. * """ class SuiteDemo (SimpleCanvasDemo): - + def __init__(self, theCanvas): SimpleCanvasDemo.__init__(self, theCanvas) self.width = 350 self.height = 350 self.demoName = "Feature Suite" self.run = False - + def createControls(self): self.controls = SuiteDemoControls(self) - - + + def drawDemo(self): self.canvas.resize(self.width, self.height) self.canvas.setBackgroundColor(Color.BLACK) - - + + def stopDemo(self): self.run = False self.canvas.setBackgroundColor(GWTCanvasConsts.TRANSPARENT) - + def getTimeSeconds(self): return time.time() % 60.0 @@ -714,7 +714,7 @@ def drawClock(self): self.canvas.translate(175, 175) self.canvas.scale(0.8, 0.8) self.canvas.rotate( (-math.pi / 2)) - + self.canvas.saveContext() self.canvas.beginPath() self.canvas.setLineWidth(7) @@ -725,12 +725,12 @@ def drawClock(self): self.canvas.arc(0, 0, 142, 0, (math.pi * 2), True) self.canvas.stroke() self.canvas.restoreContext() - + self.canvas.setStrokeStyle(Color.BLACK) self.canvas.setFillStyle(Color.WHITE) self.canvas.setLineWidth(4) self.canvas.setLineCap("round") - + # Hour marks self.canvas.saveContext() for i in range(12): @@ -739,9 +739,9 @@ def drawClock(self): self.canvas.moveTo(100, 0) self.canvas.lineTo(120, 0) self.canvas.stroke() - + self.canvas.restoreContext() - + # Minute marks self.canvas.saveContext() self.canvas.setLineWidth(2.5) @@ -751,17 +751,17 @@ def drawClock(self): self.canvas.moveTo(117, 0) self.canvas.lineTo(120, 0) self.canvas.stroke() - + self.canvas.rotate( (math.pi / 30)) - + self.canvas.restoreContext() - + sec = self.getTimeSeconds() min = self.getTimeMinutes() + sec / 60.0 hr = self.getTimeHours() + min / 60.0 self.canvas.setFillStyle(Color.BLACK) - + # write Hours self.canvas.saveContext() self.canvas.rotate( (hr * math.pi / 6 + math.pi / 360 * min + math.pi @@ -772,7 +772,7 @@ def drawClock(self): self.canvas.lineTo(80, 0) self.canvas.stroke() self.canvas.restoreContext() - + # write Minutes self.canvas.saveContext() self.canvas.rotate( (math.pi / 30 * min + math.pi / 1800 * sec)) @@ -782,7 +782,7 @@ def drawClock(self): self.canvas.lineTo(112, 0) self.canvas.stroke() self.canvas.restoreContext() - + # Write seconds self.canvas.saveContext() self.canvas.rotate( (sec * math.pi / 30)) @@ -808,10 +808,10 @@ def drawClock(self): self.canvas.arc(0, 0, 3, 0, (math.pi * 2), True) self.canvas.fill() self.canvas.restoreContext() - + self.canvas.restoreContext() Timer(1000, self) - + def drawSpirograph(self, p, r0, r, o): x1 = r0 - o y1 = 0 @@ -830,6 +830,6 @@ def drawSpirograph(self, p, r0, r, o): y1 = y2 i += 1 self.canvas.stroke() - + diff --git a/examples/hangman/HangMan.py b/examples/hangman/HangMan.py index 3c2330763..9989bee7c 100644 --- a/examples/hangman/HangMan.py +++ b/examples/hangman/HangMan.py @@ -5,9 +5,9 @@ class HangMan: def onModuleLoad(self): - self.webspace=HangManWidget() + self.webspace=HangManWidget() RootPanel().add(self.webspace) - + if __name__ == '__main__': # for pyjd, set up a web server and load the HTML from there: diff --git a/examples/hangman/HangManWidget.py b/examples/hangman/HangManWidget.py index cab4c8ef3..7fc59a12f 100644 --- a/examples/hangman/HangManWidget.py +++ b/examples/hangman/HangManWidget.py @@ -53,9 +53,9 @@ def __init__(self): self.radLevel20 = RadioButton("group0", "20+ letters") self.radLevel5.addClickListener(self.onRadioSelect) - self.radLevel10.addClickListener(self.onRadioSelect) + self.radLevel10.addClickListener(self.onRadioSelect) self.radLevel15.addClickListener(self.onRadioSelect) - self.radLevel20.addClickListener(self.onRadioSelect) + self.radLevel20.addClickListener(self.onRadioSelect) self.rad_hp = HorizontalPanel() self.rad_hp.setSpacing(4) @@ -82,7 +82,7 @@ def __init__(self): self.midrow.add(self.key_widgets[i]) else: self.botrow.add(self.key_widgets[i]) - + self.vp_main.add(self.hangdude) self.vp_main.add(self.puzzlestring) self.vp_main.add(self.toprow) @@ -104,13 +104,13 @@ def onClick(self, sender): self.score = 0 for i in range(len(self.key_widgets)): self.key_widgets[i].setEnabled(True) - if self.level == 5: + if self.level == 5: words = Wordlist_5.words - elif self.level == 10: + elif self.level == 10: words = Wordlist_10.words - elif self.level == 15: + elif self.level == 15: words = Wordlist_15.words - elif self.level == 20: + elif self.level == 20: words = Wordlist_20.words #pick a random word g = random.Random() @@ -163,7 +163,7 @@ def clear(self): def draw(self, guesses): self.context.fillStyle = '#000' - self.context.lineWidth = 2 + self.context.lineWidth = 2 if guesses == 1: self.context.fillRect(20, 280, 200,10) elif guesses == 2: diff --git a/examples/hangman/Wordlist_20.py b/examples/hangman/Wordlist_20.py index ed9db813c..d673d43e7 100644 --- a/examples/hangman/Wordlist_20.py +++ b/examples/hangman/Wordlist_20.py @@ -1,7 +1,7 @@ -words=[ -'counterrevolutionary', -'uncharacteristically', -'Antidisestablishmentarianism', -'Floccinaucinihilipilification', -'Supercalifragilisticexpialidocious' -] +words=[ +'counterrevolutionary', +'uncharacteristically', +'Antidisestablishmentarianism', +'Floccinaucinihilipilification', +'Supercalifragilisticexpialidocious' +] diff --git a/examples/infohierarchy/InfoDirectory.py b/examples/infohierarchy/InfoDirectory.py index d5a0a8c33..a53cf9763 100644 --- a/examples/infohierarchy/InfoDirectory.py +++ b/examples/infohierarchy/InfoDirectory.py @@ -30,7 +30,7 @@ def __init__(self, sink): SimplePanel.__init__(self) self.sink = sink self.caption = HTML() - self.child = None + self.child = None self.showing = False self.dragging = False self.dragStartX = 0 @@ -41,7 +41,7 @@ def __init__(self, sink): self.collapse.addClickListener(self) dock = DockPanel() dock.setSpacing(0) - + dock.add(self.collapse, DockPanel.EAST) dock.add(self.caption, DockPanel.WEST) @@ -258,7 +258,7 @@ def __init__(self): def setTitle(self, title): self.title.setHTML(title) - + def clear_items(self): for i in range(len(self.grids)): @@ -282,7 +282,7 @@ def setup_panels(self, datasets): # fname = item[0] # self.grids[i] = RightGrid(fname) # self.g.setWidget(i, 0, self.grids[i]) - + def add_html(self, html, name, index): self.data[index] = html self.names[index] = name @@ -327,7 +327,7 @@ def onCellClicked(self, sender, row, col): self.styleRow(self.selected_row, True) self.sink.select_right_grid(self.item_locations[row], self.item_names[row]) - + def styleRow(self, row, selected): if (row != -1): if (selected): @@ -387,7 +387,7 @@ def onModuleLoad(self): self.onWindowResized(width, height) Window.addWindowResizeListener(self) - + def setCollapserWidth(self, widget, width): self.horzpanel1.setCellWidth(widget, width) @@ -444,7 +444,7 @@ def get_rightpanel_datasets(self, datasets): item = datasets[i] fname = item[0] self.remote.get_rightpanel_data(fname, fname, i, self) - + def fill_right_grid(self, data): index = data.get('index') name = data.get('name') diff --git a/examples/infohierarchy/Trees.py b/examples/infohierarchy/Trees.py index c1b0737c6..08d6ac123 100644 --- a/examples/infohierarchy/Trees.py +++ b/examples/infohierarchy/Trees.py @@ -13,12 +13,12 @@ def __init__(self): self.fProto = [] self.fTree = Tree() - + self.fTree.addTreeListener(self) self.initWidget(self.fTree) self.remote = InfoServicePython() self.remote.index("", 1, self) - + def protoise_tree(self, data): if not data: @@ -36,7 +36,7 @@ def protoise_tree(self, data): def create_tree(self, data): self.fProto = self.protoise_tree(data) - + for i in range(len(self.fProto)): p = self.fProto[i] p.pathify() @@ -56,12 +56,12 @@ def onRemoteError(self, code, message, request_info): def onTreeItemSelected(self, item): pass - + def onTreeItemStateChanged(self, item): child = item.getChild(0) if hasattr(child, "isPendingItem"): item.removeItem(child) - + proto = item.getUserObject() for i in range(len(proto.children)): self.createItem(proto.children[i]) @@ -80,7 +80,7 @@ def __init__(self, text, children=None): self.item = None self.text = text self.root = '/' - + if children is not None: self.children = children diff --git a/examples/infohierarchy/public/services/jsonrpc/__init__.py b/examples/infohierarchy/public/services/jsonrpc/__init__.py index 31e7e2e2f..7e0f1f315 100644 --- a/examples/infohierarchy/public/services/jsonrpc/__init__.py +++ b/examples/infohierarchy/public/services/jsonrpc/__init__.py @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from threading import Event, Lock @@ -26,8 +26,8 @@ from json import JSONDecoder, JSONEncoder except ImportError, e: from simplejson import JSONDecoder, JSONEncoder - - + + class JSONRPCEncoder(JSONEncoder): def default(self, obj): if isinstance(obj, JSONRPCError): @@ -38,19 +38,19 @@ def default(self, obj): class Timeout(Exception): pass - + class ResponseEvent: """Event which is fired when the response is returned for a request. - - For each request sent this event is created. + + For each request sent this event is created. An application can wait for the event to create a blocking request. """ def __init__(self): self.__evt = Event() - + def waiting(self): return not self.__evt.isSet() - + def waitForResponse(self, timeOut=None): """blocks until the response arrived or timeout is reached.""" self.__evt.wait(timeOut) @@ -61,12 +61,12 @@ def waitForResponse(self, timeOut=None): raise Exception(self.response["error"]) else: return self.response["result"] - + def handleResponse(self, resp): self.response = resp self.__evt.set() - - + + class SimpleMessageHandler: def __init__(self, DecoderClass=JSONDecoder, EncoderClass=JSONRPCEncoder, messageDelimiter=""): self.decoder = DecoderClass() @@ -75,16 +75,16 @@ def __init__(self, DecoderClass=JSONDecoder, EncoderClass=JSONRPCEncoder, messa self.respEvents={} self.respLock = Lock() self.messageDelimiter=messageDelimiter - + def close(self): pass - + def send(self, data): pass - + def sendMessage(self, msg): self.send(self.encoder.encode(msg) + self.messageDelimiter) - + def handlePartialData(self, data): data = self.partialData + data.replace("\r","").replace("\n", "") msgs=[] @@ -95,32 +95,32 @@ def handlePartialData(self, data): try: (obj, pos) = self.decoder.raw_decode(data) data = data[pos:] - msgs.append(obj) + msgs.append(obj) except: break else: break self.partialData = data - + self.handleMessages(msgs) def sendNotify(self, name, args): """sends a notification object to the peer""" self.sendMessage({"method":name, "params": args}) - + def sendRequest(self, name, args): """sends a request to the peer""" (respEvt, id) = self.newResponseEvent() self.sendMessage({"id":id, "method":name, "params": args}) return respEvt - + def sendResponse(self, id, result, error): """sends a response to the peer""" self.sendMessage({"result":result, "error": error, "id":id}) - + def newResponseEvent(self): """creates a response event and adds it to a waiting list - When the reponse arrives it will be removed from the list. + When the reponse arrives it will be removed from the list. """ respEvt = ResponseEvent() self.respLock.acquire() @@ -128,36 +128,36 @@ def newResponseEvent(self): self.respEvents[eid] = respEvt self.respLock.release() return (respEvt,eid) - + def handleMessages(self, msgs): for msg in msgs: if msg.has_key("method") and msg.has_key("params"): if msg.has_key("id"): if msg["id"]: - self.handleRequest(msg) + self.handleRequest(msg) else: self.handleNotification(msg) else: self.handleNotification(msg) elif msg.has_key("result") and msg.has_key("error"): self.handleResponse(msg) - else:#unknown object + else:#unknown object self.sendResponse(None, InvalidJSONMessage()) self.close() - + def handleResponse(self, resp): """handles a response by fireing the response event for the response coming in""" id=resp["id"] evt = self.respEvents[id] del(self.respEvents[id]) evt.handleResponse(resp) - + def handleRequest(self, request): pass def handleNotification(self, notification): pass - - + + import re NameAllowedRegExp=re.compile("^[a-zA-Z]\w*$") def nameAllowed(name): @@ -167,7 +167,7 @@ def nameAllowed(name): return 1 else: return 0 - + def getMethodByName(obj, name): """searches for an object with the name given inside the object given. @@ -176,7 +176,7 @@ def getMethodByName(obj, name): try:#to get a method by asking the service obj = obj._getMethodByName(name) except: - #assumed a childObject is ment + #assumed a childObject is ment #split the name from objName.childObjName... -> [objName, childObjName, ...] #and get all objects up to the last in list with name checking from the service object names = name.split(".") @@ -185,9 +185,9 @@ def getMethodByName(obj, name): obj = getattr(obj, name) else: raise MethodNameNotAllowed() - - return obj - + + return obj + class SimpleServiceHandler(SimpleMessageHandler): @@ -198,20 +198,20 @@ def __init__(self, service, DecoderClass=JSONDecoder, EncoderClass=JSONRPCEncode service._newConnection(self) except: pass - + def close(self): try: self.service._closingConnection(self) except: pass - + def handleRequest(self, req): """handles a request by calling the appropriete method the service exposes""" name = req["method"] params = req["params"] id=req["id"] obj=None - try: #to get a callable obj + try: #to get a callable obj obj = getMethodByName(self.service, name) except MethodNameNotAllowed,e: self.sendResponse(id, None, e) @@ -228,17 +228,17 @@ def handleRequest(self, req): except: #error inside the callable object s=getTracebackStr() self.sendResponse(id, None, s) - + def handleNotification(self, req): """handles a notification request by calling the appropriete method the service exposes""" name = req["method"] params = req["params"] - try: #to get a callable obj + try: #to get a callable obj obj = getMethodByName(self.service, name) rslt = obj(*params) except: pass - - - + + + diff --git a/examples/infohierarchy/public/services/jsonrpc/apacheServiceHandler.py b/examples/infohierarchy/public/services/jsonrpc/apacheServiceHandler.py index 170d98561..00ac9bd6c 100644 --- a/examples/infohierarchy/public/services/jsonrpc/apacheServiceHandler.py +++ b/examples/infohierarchy/public/services/jsonrpc/apacheServiceHandler.py @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from mod_python import apache from jsonrpc import SimpleServiceHandler @@ -25,7 +25,7 @@ class ModPyHandler(SimpleServiceHandler): def send(self, data): self.req.write(data) self.req.flush() - + def handle(self, req): self.req = req req.content_type = "text/plain" @@ -35,18 +35,18 @@ def handle(self, req): from mod_python import apache import os, sys -def handler(req): +def handler(req): (modulePath, fileName) = os.path.split(req.filename) (moduleName, ext) = os.path.splitext(fileName) - + if not os.path.exists(os.path.join(modulePath, moduleName + ".py")): return apache.HTTP_NOT_FOUND - + if not modulePath in sys.path: sys.path.insert(0, modulePath) - + module = apache.import_module(moduleName, log=1) - + if hasattr(module, "getService"): service = module.getService() elif hasattr(module, "service"): @@ -55,8 +55,8 @@ def handler(req): service = module.Service() else: return apache.HTTP_SERVICE_UNAVAILABLE - + ModPyHandler(service, messageDelimiter="\n").handle(req) - + return apache.OK - + diff --git a/examples/infohierarchy/public/services/jsonrpc/cgihandler.py b/examples/infohierarchy/public/services/jsonrpc/cgihandler.py index 1cf586efb..ced1832ec 100644 --- a/examples/infohierarchy/public/services/jsonrpc/cgihandler.py +++ b/examples/infohierarchy/public/services/jsonrpc/cgihandler.py @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from jsonrpc import SimpleServiceHandler @@ -27,10 +27,10 @@ def __init__(self, service, messageDelimiter="\n"): self.sendData =[] SimpleServiceHandler.__init__(self, service, messageDelimiter=messageDelimiter) - + def send(self, data): self.sendData.append(data) - + def handle(self): try: contLen=int(os.environ['CONTENT_LENGTH']) @@ -38,25 +38,25 @@ def handle(self): except: data = "" #execute the request - self.handlePartialData(data) + self.handlePartialData(data) self.sendReply() self.close() - + def sendReply(self): data = "\n".join(self.sendData) response = "Content-Type: text/plain\n" response += "Content-Length: %d\n\n" % len(data) response += data - + #on windows all \n are converted to \r\n if stdout is a terminal and is not set to binary mode :( #this will then cause an incorrect Content-length. #I have only experienced this problem with apache on Win so far. - if sys.platform == "win32": - import msvcrt + if sys.platform == "win32": + import msvcrt msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) #put out the response sys.stdout.write(response) - - + + def handleCGIRequest(service): CGIHandler(service,messageDelimiter="\n").handle() diff --git a/examples/infohierarchy/public/services/jsonrpc/errors.py b/examples/infohierarchy/public/services/jsonrpc/errors.py index 597f78010..deaab48d8 100644 --- a/examples/infohierarchy/public/services/jsonrpc/errors.py +++ b/examples/infohierarchy/public/services/jsonrpc/errors.py @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ class JSONRPCError: @@ -34,8 +34,8 @@ class InvalidMethodParameters(JSONRPCError): pass class MethodNameNotAllowed(JSONRPCError): pass - - + + def getTracebackStr(): import traceback diff --git a/examples/infohierarchy/public/services/jsonrpc/http.py b/examples/infohierarchy/public/services/jsonrpc/http.py index 42f3c6791..ca19fe02b 100644 --- a/examples/infohierarchy/public/services/jsonrpc/http.py +++ b/examples/infohierarchy/public/services/jsonrpc/http.py @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from jsonrpc import SimpleServiceHandler @@ -26,9 +26,8 @@ class HTTPClientConnectionHandler(SimpleServiceHandler): def __init__(self, url, service,messageDelimiter=""): self.url = url SimpleServiceHandler.__init__(self, service,messageDelimiter=messageDelimiter) - + def send(self, data): req = urllib2.Request(self.url, data) resp = urllib2.urlopen(req) self.handlePartialData(resp.read()) - \ No newline at end of file diff --git a/examples/infohierarchy/public/services/jsonrpc/proxy.py b/examples/infohierarchy/public/services/jsonrpc/proxy.py index 6cb7399af..7496b3900 100644 --- a/examples/infohierarchy/public/services/jsonrpc/proxy.py +++ b/examples/infohierarchy/public/services/jsonrpc/proxy.py @@ -15,20 +15,20 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ - + class PeerObjectProxy(object): """creates a peer object which will send requests to the remote service when invoked.""" def __init__(self, name, conn): self._name = name self._conn = conn - + def notify(self, *args): self._conn.sendNotify(self._name, args) - + def __call__(self, *args): evt = self._conn.sendRequest(self._name, args) return evt.waitForResponse() @@ -40,7 +40,7 @@ def __getattr__(self, name): class PeerProxy: def __init__(self, connectionHandler): self._connectionHandler = connectionHandler - + def __getattr__(self, name): return PeerObjectProxy(name, self._connectionHandler) @@ -55,14 +55,14 @@ def __init__(self, url, localService=None, messageDelimiter=""): from jsonrpc.socketserver import SocketServiceHandler import socket from threading import Thread - + (host, port)= m.groups() port = int(port) - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) conn = SocketServiceHandler(s, localService,messageDelimiter=messageDelimiter) PeerProxy.__init__(self, conn) - + t=Thread(target=conn.receiveForever) t.setDaemon(True) t.start() @@ -71,6 +71,6 @@ def __init__(self, url, localService=None, messageDelimiter=""): conn= HTTPClientConnectionHandler(url, localService,messageDelimiter=messageDelimiter) PeerProxy.__init__(self, conn) - + diff --git a/examples/infohierarchy/public/services/jsonrpc/socketserver.py b/examples/infohierarchy/public/services/jsonrpc/socketserver.py index 68011f872..2b52ca42c 100644 --- a/examples/infohierarchy/public/services/jsonrpc/socketserver.py +++ b/examples/infohierarchy/public/services/jsonrpc/socketserver.py @@ -15,19 +15,19 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from jsonrpc import SimpleServiceHandler import socket from threading import Thread - - + + class SocketServiceHandler(SimpleServiceHandler): def __init__(self, socket, service, messageDelimiter=""): self.socket = socket SimpleServiceHandler.__init__(self, service, messageDelimiter=messageDelimiter) - + def receiveForever(self): while 1: try: @@ -41,10 +41,10 @@ def receiveForever(self): return else: self.handlePartialData(data) - + def send(self, data): self.socket.send(data) - + def close(self): SimpleServiceHandler.close(self) if self.socket: @@ -53,7 +53,7 @@ def close(self): self.socket = None except: pass - + class TCPServiceServer: @@ -61,22 +61,22 @@ def __init__(self, service, ConnectionHandler = SocketServiceHandler, messageDel self.service = service self.ConnectionHandler = ConnectionHandler self.messageDelimiter=messageDelimiter - + def serve(self, address): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.socket.bind(address) + self.socket.bind(address) self.socket.listen(5) print "serving", self.socket while 1: (conn,addr) = self.socket.accept() self.acceptConnection(conn) - + def acceptConnection(self, conn): self.handleConnection(conn) - + def handleConnection(self, conn): self.ConnectionHandler(conn, self.service, messageDelimiter=self.messageDelimiter).receiveForever() - + class ThreadingMixin: @@ -87,5 +87,5 @@ def acceptConnection(self, conn): class ThreadedTCPServiceServer(ThreadingMixin, TCPServiceServer): pass - - + + diff --git a/examples/jsimport/examplejs.py b/examples/jsimport/examplejs.py index bf1eba090..373b96936 100644 --- a/examples/jsimport/examplejs.py +++ b/examples/jsimport/examplejs.py @@ -22,7 +22,7 @@ jsimport("example.js") def main(): - global examplevar + global examplevar #examplevar is actually "out of modules", in a super scope log.debug(examplevar) diff --git a/examples/jsonrpc/JSONRPCExample.py b/examples/jsonrpc/JSONRPCExample.py index f715f4766..b0f812974 100644 --- a/examples/jsonrpc/JSONRPCExample.py +++ b/examples/jsonrpc/JSONRPCExample.py @@ -19,8 +19,8 @@ def onModuleLoad(self): self.METHOD_UPPERCASE = "UPPERCASE" self.METHOD_LOWERCASE = "lowercase" self.METHOD_NONEXISTANT = "Non existant" - self.methods = [self.METHOD_ECHO, self.METHOD_REVERSE, - self.METHOD_UPPERCASE, self.METHOD_LOWERCASE, + self.methods = [self.METHOD_ECHO, self.METHOD_REVERSE, + self.METHOD_UPPERCASE, self.METHOD_LOWERCASE, self.METHOD_NONEXISTANT] self.remote_php = EchoServicePHP() @@ -37,7 +37,7 @@ def onModuleLoad(self): """) self.text_area.setCharacterWidth(80) self.text_area.setVisibleLines(8) - + self.method_list = ListBox() self.method_list.setName("hello") self.method_list.setVisibleItemCount(1) @@ -57,7 +57,7 @@ def onModuleLoad(self): buttons.add(self.button_php) buttons.add(self.button_py) buttons.setSpacing(8) - + info = """

JSON-RPC Example

This example demonstrates the calling of server services with JSON-RPC. @@ -65,14 +65,14 @@ def onModuleLoad(self):

Enter some text below, and press a button to send the text to an Echo service on your server. An echo service simply sends the exact same text back that it receives.

""" - + panel = VerticalPanel() panel.add(HTML(info)) panel.add(self.text_area) panel.add(method_panel) panel.add(buttons) panel.add(self.status) - + RootPanel().add(panel) def onClick(self, sender): @@ -117,7 +117,7 @@ def onRemoteError(self, code, errobj, request_info): # } message = errobj['message'] if code != 0: - self.status.setText("HTTP error %d: %s" % + self.status.setText("HTTP error %d: %s" % (code, message)) else: code = errobj['code'] diff --git a/examples/jsonrpc/public/services/EchoService.py b/examples/jsonrpc/public/services/EchoService.py index e9be35ede..07ecf0e00 100755 --- a/examples/jsonrpc/public/services/EchoService.py +++ b/examples/jsonrpc/public/services/EchoService.py @@ -22,4 +22,4 @@ def lowercase(self, msg): # this is if JSONService.py is run from mod_python: # rename .htaccess.mod_python to .htaccess to activate, # and restart Apache2 - from jsonrpc.apacheServiceHandler import handler + from jsonrpc.apacheServiceHandler import handler diff --git a/examples/jsonrpc/public/services/jsonrpc/__init__.py b/examples/jsonrpc/public/services/jsonrpc/__init__.py index a9697df4c..05bfcac75 100644 --- a/examples/jsonrpc/public/services/jsonrpc/__init__.py +++ b/examples/jsonrpc/public/services/jsonrpc/__init__.py @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from threading import Event, Lock @@ -26,31 +26,31 @@ from simplejson import JSONDecoder, JSONEncoder except ImportError: from json import JSONDecoder, JSONEncoder - - -class JSONRPCEncoder(JSONEncoder): - def default(self, obj): - if isinstance(obj, JSONRPCError): - return obj.__class__.__name__ + + +class JSONRPCEncoder(JSONEncoder): + def default(self, obj): + if isinstance(obj, JSONRPCError): + return obj.__class__.__name__ else: return JSONEncoder.default(self, obj) class Timeout(Exception): pass - + class ResponseEvent: """Event which is fired when the response is returned for a request. - - For each request sent this event is created. + + For each request sent this event is created. An application can wait for the event to create a blocking request. """ def __init__(self): self.__evt = Event() - + def waiting(self): return not self.__evt.isSet() - + def waitForResponse(self, timeOut=None): """blocks until the response arrived or timeout is reached.""" self.__evt.wait(timeOut) @@ -61,12 +61,12 @@ def waitForResponse(self, timeOut=None): raise Exception(self.response["error"]) else: return self.response["result"] - + def handleResponse(self, resp): self.response = resp self.__evt.set() - - + + class SimpleMessageHandler: def __init__(self, DecoderClass=JSONDecoder, EncoderClass=JSONRPCEncoder, messageDelimiter=""): self.decoder = DecoderClass() @@ -75,16 +75,16 @@ def __init__(self, DecoderClass=JSONDecoder, EncoderClass=JSONRPCEncoder, messa self.respEvents={} self.respLock = Lock() self.messageDelimiter=messageDelimiter - + def close(self): pass - + def send(self, data): pass - + def sendMessage(self, msg): self.send(self.encoder.encode(msg) + self.messageDelimiter) - + def handlePartialData(self, data): data = self.partialData + data.replace("\r","").replace("\n", "") msgs=[] @@ -95,32 +95,32 @@ def handlePartialData(self, data): try: (obj, pos) = self.decoder.raw_decode(data) data = data[pos:] - msgs.append(obj) + msgs.append(obj) except: break else: break self.partialData = data - + self.handleMessages(msgs) def sendNotify(self, name, args): """sends a notification object to the peer""" self.sendMessage({"method":name, "params": args}) - + def sendRequest(self, name, args): """sends a request to the peer""" (respEvt, id) = self.newResponseEvent() self.sendMessage({"id":id, "method":name, "params": args}) return respEvt - + def sendResponse(self, id, result, error): """sends a response to the peer""" self.sendMessage({"result":result, "error": error, "id":id}) - + def newResponseEvent(self): """creates a response event and adds it to a waiting list - When the reponse arrives it will be removed from the list. + When the reponse arrives it will be removed from the list. """ respEvt = ResponseEvent() self.respLock.acquire() @@ -128,36 +128,36 @@ def newResponseEvent(self): self.respEvents[eid] = respEvt self.respLock.release() return (respEvt,eid) - + def handleMessages(self, msgs): for msg in msgs: if msg.has_key("method") and msg.has_key("params"): if msg.has_key("id"): if msg["id"]: - self.handleRequest(msg) + self.handleRequest(msg) else: self.handleNotification(msg) else: self.handleNotification(msg) elif msg.has_key("result") and msg.has_key("error"): self.handleResponse(msg) - else:#unknown object + else:#unknown object self.sendResponse(None, InvalidJSONMessage()) self.close() - + def handleResponse(self, resp): """handles a response by fireing the response event for the response coming in""" id=resp["id"] evt = self.respEvents[id] del(self.respEvents[id]) evt.handleResponse(resp) - + def handleRequest(self, request): pass def handleNotification(self, notification): pass - - + + import re NameAllowedRegExp=re.compile("^[a-zA-Z]\w*$") def nameAllowed(name): @@ -167,7 +167,7 @@ def nameAllowed(name): return 1 else: return 0 - + def getMethodByName(obj, name): """searches for an object with the name given inside the object given. @@ -176,7 +176,7 @@ def getMethodByName(obj, name): try:#to get a method by asking the service obj = obj._getMethodByName(name) except: - #assumed a childObject is ment + #assumed a childObject is ment #split the name from objName.childObjName... -> [objName, childObjName, ...] #and get all objects up to the last in list with name checking from the service object names = name.split(".") @@ -185,9 +185,9 @@ def getMethodByName(obj, name): obj = getattr(obj, name) else: raise MethodNameNotAllowed() - - return obj - + + return obj + class SimpleServiceHandler(SimpleMessageHandler): @@ -198,20 +198,20 @@ def __init__(self, service, DecoderClass=JSONDecoder, EncoderClass=JSONRPCEncode service._newConnection(self) except: pass - + def close(self): try: self.service._closingConnection(self) except: pass - + def handleRequest(self, req): """handles a request by calling the appropriete method the service exposes""" name = req["method"] params = req["params"] id=req["id"] obj=None - try: #to get a callable obj + try: #to get a callable obj obj = getMethodByName(self.service, name) except MethodNameNotAllowed,e: self.sendResponse(id, None, e) @@ -228,17 +228,17 @@ def handleRequest(self, req): except: #error inside the callable object s=getTracebackStr() self.sendResponse(id, None, s) - + def handleNotification(self, req): """handles a notification request by calling the appropriete method the service exposes""" name = req["method"] params = req["params"] - try: #to get a callable obj + try: #to get a callable obj obj = getMethodByName(self.service, name) rslt = obj(*params) except: pass - - - + + + diff --git a/examples/jsonrpc/public/services/jsonrpc/apacheServiceHandler.py b/examples/jsonrpc/public/services/jsonrpc/apacheServiceHandler.py index e41ab4645..00ac9bd6c 100644 --- a/examples/jsonrpc/public/services/jsonrpc/apacheServiceHandler.py +++ b/examples/jsonrpc/public/services/jsonrpc/apacheServiceHandler.py @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from mod_python import apache from jsonrpc import SimpleServiceHandler @@ -25,28 +25,28 @@ class ModPyHandler(SimpleServiceHandler): def send(self, data): self.req.write(data) self.req.flush() - + def handle(self, req): self.req = req req.content_type = "text/plain" self.handlePartialData(req.read()) - self.close() + self.close() -from mod_python import apache +from mod_python import apache import os, sys - -def handler(req): + +def handler(req): (modulePath, fileName) = os.path.split(req.filename) (moduleName, ext) = os.path.splitext(fileName) - + if not os.path.exists(os.path.join(modulePath, moduleName + ".py")): return apache.HTTP_NOT_FOUND - + if not modulePath in sys.path: sys.path.insert(0, modulePath) - + module = apache.import_module(moduleName, log=1) - + if hasattr(module, "getService"): service = module.getService() elif hasattr(module, "service"): @@ -55,8 +55,8 @@ def handler(req): service = module.Service() else: return apache.HTTP_SERVICE_UNAVAILABLE - + ModPyHandler(service, messageDelimiter="\n").handle(req) - + return apache.OK - + diff --git a/examples/jsonrpc/public/services/jsonrpc/cgihandler.py b/examples/jsonrpc/public/services/jsonrpc/cgihandler.py index 1cf586efb..ced1832ec 100644 --- a/examples/jsonrpc/public/services/jsonrpc/cgihandler.py +++ b/examples/jsonrpc/public/services/jsonrpc/cgihandler.py @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from jsonrpc import SimpleServiceHandler @@ -27,10 +27,10 @@ def __init__(self, service, messageDelimiter="\n"): self.sendData =[] SimpleServiceHandler.__init__(self, service, messageDelimiter=messageDelimiter) - + def send(self, data): self.sendData.append(data) - + def handle(self): try: contLen=int(os.environ['CONTENT_LENGTH']) @@ -38,25 +38,25 @@ def handle(self): except: data = "" #execute the request - self.handlePartialData(data) + self.handlePartialData(data) self.sendReply() self.close() - + def sendReply(self): data = "\n".join(self.sendData) response = "Content-Type: text/plain\n" response += "Content-Length: %d\n\n" % len(data) response += data - + #on windows all \n are converted to \r\n if stdout is a terminal and is not set to binary mode :( #this will then cause an incorrect Content-length. #I have only experienced this problem with apache on Win so far. - if sys.platform == "win32": - import msvcrt + if sys.platform == "win32": + import msvcrt msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) #put out the response sys.stdout.write(response) - - + + def handleCGIRequest(service): CGIHandler(service,messageDelimiter="\n").handle() diff --git a/examples/jsonrpc/public/services/jsonrpc/errors.py b/examples/jsonrpc/public/services/jsonrpc/errors.py index 597f78010..deaab48d8 100644 --- a/examples/jsonrpc/public/services/jsonrpc/errors.py +++ b/examples/jsonrpc/public/services/jsonrpc/errors.py @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ class JSONRPCError: @@ -34,8 +34,8 @@ class InvalidMethodParameters(JSONRPCError): pass class MethodNameNotAllowed(JSONRPCError): pass - - + + def getTracebackStr(): import traceback diff --git a/examples/jsonrpc/public/services/jsonrpc/http.py b/examples/jsonrpc/public/services/jsonrpc/http.py index 42f3c6791..ca19fe02b 100644 --- a/examples/jsonrpc/public/services/jsonrpc/http.py +++ b/examples/jsonrpc/public/services/jsonrpc/http.py @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from jsonrpc import SimpleServiceHandler @@ -26,9 +26,8 @@ class HTTPClientConnectionHandler(SimpleServiceHandler): def __init__(self, url, service,messageDelimiter=""): self.url = url SimpleServiceHandler.__init__(self, service,messageDelimiter=messageDelimiter) - + def send(self, data): req = urllib2.Request(self.url, data) resp = urllib2.urlopen(req) self.handlePartialData(resp.read()) - \ No newline at end of file diff --git a/examples/jsonrpc/public/services/jsonrpc/proxy.py b/examples/jsonrpc/public/services/jsonrpc/proxy.py index 6cb7399af..7496b3900 100644 --- a/examples/jsonrpc/public/services/jsonrpc/proxy.py +++ b/examples/jsonrpc/public/services/jsonrpc/proxy.py @@ -15,20 +15,20 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ - + class PeerObjectProxy(object): """creates a peer object which will send requests to the remote service when invoked.""" def __init__(self, name, conn): self._name = name self._conn = conn - + def notify(self, *args): self._conn.sendNotify(self._name, args) - + def __call__(self, *args): evt = self._conn.sendRequest(self._name, args) return evt.waitForResponse() @@ -40,7 +40,7 @@ def __getattr__(self, name): class PeerProxy: def __init__(self, connectionHandler): self._connectionHandler = connectionHandler - + def __getattr__(self, name): return PeerObjectProxy(name, self._connectionHandler) @@ -55,14 +55,14 @@ def __init__(self, url, localService=None, messageDelimiter=""): from jsonrpc.socketserver import SocketServiceHandler import socket from threading import Thread - + (host, port)= m.groups() port = int(port) - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) conn = SocketServiceHandler(s, localService,messageDelimiter=messageDelimiter) PeerProxy.__init__(self, conn) - + t=Thread(target=conn.receiveForever) t.setDaemon(True) t.start() @@ -71,6 +71,6 @@ def __init__(self, url, localService=None, messageDelimiter=""): conn= HTTPClientConnectionHandler(url, localService,messageDelimiter=messageDelimiter) PeerProxy.__init__(self, conn) - + diff --git a/examples/jsonrpc/public/services/jsonrpc/socketserver.py b/examples/jsonrpc/public/services/jsonrpc/socketserver.py index 7c9d44f86..2b52ca42c 100644 --- a/examples/jsonrpc/public/services/jsonrpc/socketserver.py +++ b/examples/jsonrpc/public/services/jsonrpc/socketserver.py @@ -15,19 +15,19 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from jsonrpc import SimpleServiceHandler import socket from threading import Thread - - + + class SocketServiceHandler(SimpleServiceHandler): def __init__(self, socket, service, messageDelimiter=""): self.socket = socket SimpleServiceHandler.__init__(self, service, messageDelimiter=messageDelimiter) - + def receiveForever(self): while 1: try: @@ -39,12 +39,12 @@ def receiveForever(self): if self.socket: self.close() return - else: + else: self.handlePartialData(data) - + def send(self, data): self.socket.send(data) - + def close(self): SimpleServiceHandler.close(self) if self.socket: @@ -53,7 +53,7 @@ def close(self): self.socket = None except: pass - + class TCPServiceServer: @@ -61,22 +61,22 @@ def __init__(self, service, ConnectionHandler = SocketServiceHandler, messageDel self.service = service self.ConnectionHandler = ConnectionHandler self.messageDelimiter=messageDelimiter - + def serve(self, address): - self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.socket.bind(address) + self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.socket.bind(address) self.socket.listen(5) print "serving", self.socket while 1: (conn,addr) = self.socket.accept() self.acceptConnection(conn) - + def acceptConnection(self, conn): self.handleConnection(conn) - + def handleConnection(self, conn): self.ConnectionHandler(conn, self.service, messageDelimiter=self.messageDelimiter).receiveForever() - + class ThreadingMixin: @@ -87,5 +87,5 @@ def acceptConnection(self, conn): class ThreadedTCPServiceServer(ThreadingMixin, TCPServiceServer): pass - - + + diff --git a/examples/kitchensink/Buttons.py b/examples/kitchensink/Buttons.py index 0f156554b..930614380 100644 --- a/examples/kitchensink/Buttons.py +++ b/examples/kitchensink/Buttons.py @@ -25,13 +25,13 @@ def __init__(self): hp.setSpacing(8) hp.add(normalButton) hp.add(disabledButton) - + hp=HorizontalPanel() panel.add(hp) hp.setSpacing(8) hp.add(normalCheck) hp.add(disabledCheck) - + hp=HorizontalPanel() panel.add(hp) hp.setSpacing(8) @@ -39,11 +39,11 @@ def __init__(self): hp.add(radio1) hp.add(radio2) hp.add(radio3) - + disabledButton.setEnabled(False) disabledCheck.setEnabled(False) radio2.setEnabled(False) - + panel.setSpacing(8) self.initWidget(panel) diff --git a/examples/kitchensink/Frames.py b/examples/kitchensink/Frames.py index 821c8616d..16897a861 100644 --- a/examples/kitchensink/Frames.py +++ b/examples/kitchensink/Frames.py @@ -5,11 +5,11 @@ class Frames(Sink): def __init__(self): Sink.__init__(self) self.frame=Frame(self.baseURL() + "rembrandt/LaMarcheNocturne.html") - + self.frame.setWidth("100%") self.frame.setHeight("48em") self.initWidget(self.frame) - + def init(): text="If you need to include multiple pages of good ol' static HTML, it's easy to do using the Frame class." return SinkInfo("Frames", text, Frames) diff --git a/examples/kitchensink/Images.py b/examples/kitchensink/Images.py index d6fcd2ab5..5760bffd7 100644 --- a/examples/kitchensink/Images.py +++ b/examples/kitchensink/Images.py @@ -17,30 +17,30 @@ def __init__(self): for i in range(len(self.sImages)): self.sImages[i]=self.baseURL() + self.sImages[i] - + self.image.addLoadListener(self) self.prevButton.addClickListener(self) self.nextButton.addClickListener(self) - + topPanel = DockPanel() topPanel.setVerticalAlignment(HasAlignment.ALIGN_MIDDLE) topPanel.add(self.prevButton, DockPanel.WEST) topPanel.add(self.nextButton, DockPanel.EAST) topPanel.add(self.loadingImage, DockPanel.CENTER) - + panel = VerticalPanel() panel.setHorizontalAlignment(HasAlignment.ALIGN_CENTER) panel.add(HTML("

A Bit of Rembrandt

", True)) panel.add(topPanel) panel.add(self.image) - + panel.setWidth("100%") self.initWidget(panel) self.image.setStyleName("ks-images-Image") self.nextButton.setStyleName("ks-images-Button") self.prevButton.setStyleName("ks-images-Button") - - self.loadImage(0) + + self.loadImage(0) def onClick(self, sender): if sender==self.prevButton: diff --git a/examples/kitchensink/KitchenSink.py b/examples/kitchensink/KitchenSink.py index 5394d6618..eac31c507 100644 --- a/examples/kitchensink/KitchenSink.py +++ b/examples/kitchensink/KitchenSink.py @@ -43,7 +43,7 @@ def onModuleLoad(self): self.description=HTML() self.sink_list=SinkList() self.panel=DockPanel() - + self.loadSinks() self.sinkContainer = DockPanel() self.sinkContainer.setStyleName("ks-Sink") @@ -94,7 +94,7 @@ def show(self, info, affectHistory): self.sinkContainer.setCellHeight(self.curSink, "100%") self.sinkContainer.setCellVerticalAlignment(self.curSink, HasAlignment.ALIGN_TOP) self.curSink.onShow() - + def loadSinks(self): self.sink_list.add(Info.init()) self.sink_list.add(Buttons.init()) diff --git a/examples/kitchensink/Layouts.py b/examples/kitchensink/Layouts.py index 7550fff38..d73908b0c 100644 --- a/examples/kitchensink/Layouts.py +++ b/examples/kitchensink/Layouts.py @@ -11,7 +11,7 @@ from pyjamas.ui.MenuBar import MenuBar from pyjamas.ui.MenuItem import MenuItem from pyjamas.ui.ScrollPanel import ScrollPanel -from pyjamas.ui.DisclosurePanel import DisclosurePanel +from pyjamas.ui.DisclosurePanel import DisclosurePanel from Logger import Logger from pyjamas import DOM @@ -19,20 +19,20 @@ class Layouts(Sink): def __init__(self): Sink.__init__(self) - text="""This is a ScrollPanel contained at - the center of a DockPanel. - By putting some fairly large contents - in the middle and setting its size explicitly, it becomes a - scrollable area within the page, but without requiring the use of + text="""This is a ScrollPanel contained at + the center of a DockPanel. + By putting some fairly large contents + in the middle and setting its size explicitly, it becomes a + scrollable area within the page, but without requiring the use of an IFRAME. - Here's quite a bit more meaningless text that will serve primarily - to make this thing scroll off the bottom of its visible area. - Otherwise, you might have to make it really, really small in order + Here's quite a bit more meaningless text that will serve primarily + to make this thing scroll off the bottom of its visible area. + Otherwise, you might have to make it really, really small in order to see the nifty scroll bars!""" - + contents = HTML(text) scroller = ScrollPanel(contents, StyleName="ks-layouts-Scroller") - + dock = DockPanel(HorizontalAlignment=HasAlignment.ALIGN_CENTER, Spacing=10) north0 = HTML("This is the first north component", True) @@ -46,7 +46,7 @@ def __init__(self): dock.add(west, DockPanel.WEST) dock.add(north1, DockPanel.NORTH) dock.add(scroller, DockPanel.CENTER) - + #Logger.write("Layouts", "TODO: flowpanel") flow = FlowPanel() for i in range(8): @@ -76,11 +76,11 @@ def __init__(self): #Logger.write("Layouts", "TODO: htmlpanel") id = HTMLPanel.createUniqueId() - text="""This is an HTMLPanel. It allows you to add + text="""This is an HTMLPanel. It allows you to add components inside existing HTML, like this: Notice how the menu just fits snugly in there? Cute.""" % id html = HTMLPanel(text) - + DOM.setStyleAttribute(menu.getElement(), "display", "inline") html.add(menu, id) @@ -90,7 +90,7 @@ def __init__(self): panel = VerticalPanel(Spacing=8, HorizontalAlignment=HasAlignment.ALIGN_CENTER) - + panel.add(self.makeLabel("Dock Panel")) panel.add(dock) panel.add(self.makeLabel("Flow Panel")) @@ -103,7 +103,7 @@ def __init__(self): panel.add(html) panel.add(self.makeLabel("Disclosure Panel")) panel.add(disclose) - + self.initWidget(panel) self.setStyleName("ks-layouts") @@ -118,11 +118,11 @@ def makeLabel(self, caption): def init(): text="""This page demonstrates some of the basic GWT panels, each of which - arranges its contained widgets differently. - These panels are designed to take advantage of the browser's - built-in layout mechanics, which keeps the user interface snappy - and helps your AJAX code play nicely with existing HTML. - On the other hand, if you need pixel-perfect control, - you can tweak things at a low level using the + arranges its contained widgets differently. + These panels are designed to take advantage of the browser's + built-in layout mechanics, which keeps the user interface snappy + and helps your AJAX code play nicely with existing HTML. + On the other hand, if you need pixel-perfect control, + you can tweak things at a low level using the DOM class.""" return SinkInfo("Layouts", text, Layouts) diff --git a/examples/kitchensink/Lists.py b/examples/kitchensink/Lists.py index 6a76b56a9..e1bd23dbb 100644 --- a/examples/kitchensink/Lists.py +++ b/examples/kitchensink/Lists.py @@ -21,7 +21,7 @@ def __init__(self): self.echo=Label() self.combo.addChangeListener(self) - + for i in range(len(self.sStrings)): txt = "List %d" % i self.combo.addItem(txt) @@ -31,19 +31,19 @@ def __init__(self): self.fillList(0) self.list.setItemSelected(0, False) self.list.setItemSelected(1, True) - + self.list.addChangeListener(self) - + horz = HorizontalPanel(VerticalAlignment=HasAlignment.ALIGN_TOP, Spacing=8) horz.add(self.combo) horz.add(self.list) - + panel = VerticalPanel(HorizontalAlignment=HasAlignment.ALIGN_LEFT) panel.add(horz) panel.add(self.echo) self.initWidget(panel) - + self.echoSelection() def onChange(self, sender): @@ -54,7 +54,7 @@ def onChange(self, sender): def onShow(self): pass - + def fillList(self, idx): self.list.clear() strings = self.sStrings[idx] diff --git a/examples/kitchensink/Logger.py b/examples/kitchensink/Logger.py index 4751a93d0..1d5ab2b23 100644 --- a/examples/kitchensink/Logger.py +++ b/examples/kitchensink/Logger.py @@ -2,7 +2,7 @@ class Logger(Grid): instances = [] - + def __init__(self): Logger.instances.append(self) @@ -14,49 +14,49 @@ def __init__(self): self.resize(len(self.targets)+1, 2) self.setBorderWidth("1") self.counter=0 - + self.setHTML(0, 0, "Log") self.setText(1, 0, "app") for i in range(len(self.targets)): target=self.targets[i] self.setText(i+1, 0, target) - + @classmethod def getSingleton(self): return Logger.singleton - + def setSingleton(self): Logger.singleton = self - + def addTarget(self, target): self.targets.append(target) self.resize(len(self.targets)+1, 2) self.setText(len(self.targets), 0, target) return self.targets.index(target) - + @classmethod - def write(cls, target, message): + def write(cls, target, message): for logger in cls.instances: logger.onMessage(target, message) - + def onMessage(self, target, message): self.counter+=1 - + if target=='': target='app' target_idx=self.targets.index(target) - + # add new target if target_idx<0: target_idx=self.addTarget(target) - - target_row=target_idx+1 + + target_row=target_idx+1 old_text=self.getHTML(target_row, 1) log_line=self.counter + ": " + message if old_text==' ': - new_text=log_line + new_text=log_line else: new_text=old_text + "
" + log_line - self.setHTML(target_row, 1, new_text) + self.setHTML(target_row, 1, new_text) diff --git a/examples/kitchensink/Menus.py b/examples/kitchensink/Menus.py index afc30eb3d..1d3545754 100644 --- a/examples/kitchensink/Menus.py +++ b/examples/kitchensink/Menus.py @@ -11,12 +11,12 @@ class Menus(Sink): def __init__(self): Sink.__init__(self) self.menu = MenuBar() - + subMenu = MenuBar(True) subMenu.addItem("Code", True, self) subMenu.addItem("Strikethrough", True, self) subMenu.addItem("Underlined", True, self) - + menu0 = MenuBar(True) menu0.addItem("Bold", True, self) menu0.addItem("Italicized", True, self) @@ -30,13 +30,13 @@ def __init__(self): menu2.addItem("Bling", self) menu2.addItem("Ginormous", self) menu2.addItem("w00t!", True, self) - + self.menu.addItem(MenuItem("Style", menu0)) self.menu.addItem(MenuItem("Fruit", menu1)) self.menu.addItem(MenuItem("Term", menu2)) - + self.menu.setWidth("100%") - + self.panel = VerticalPanel() self.context = HTML("""Right-Click me
to show a context menu.
Left-click me
to do absolutely nothing.""") @@ -59,14 +59,14 @@ def onContextMenu(self, sender): x = DOM.eventGetClientX(event) + 2 y = DOM.eventGetClientY(event) + 2 - + popup = ContextMenuPopupPanel(subMenu) popup.showAt(x, y) def execute(self): Window.alert("Thank you for selecting a menu item.") - + def onShow(self): pass diff --git a/examples/kitchensink/Popups.py b/examples/kitchensink/Popups.py index 6fbfa469d..e4b4ddc99 100644 --- a/examples/kitchensink/Popups.py +++ b/examples/kitchensink/Popups.py @@ -19,18 +19,18 @@ def __init__(self): self.fDialogButton = Button("Show Dialog", self) self.fPopupButton = Button("Show Popup", self) self.fMultipleDialogButton = Button("Show muliple dialogs", self) - + panel = VerticalPanel() panel.add(self.fPopupButton) panel.add(self.fDialogButton) panel.add(self.fMultipleDialogButton) - + list = ListBox() list.setVisibleItemCount(5) for i in range(10): list.addItem("list item %d" % i) panel.add(list) - + panel.setSpacing(8) self.initWidget(panel) @@ -78,25 +78,25 @@ class MyDialog(DialogBox): def __init__(self, baseURL): DialogBox.__init__(self, glass=True) self.setText("Sample DialogBox with embedded Frame") - + iframe = Frame(baseURL + "rembrandt/LaMarcheNocturne.html") closeButton = Button("Close", self) msg = HTML("
This is an example of a standard dialog box component.
You can put pretty much anything you like into it,
such as the following IFRAME:
", True) - + dock = DockPanel() dock.setSpacing(4) - + dock.add(closeButton, DockPanel.SOUTH) dock.add(msg, DockPanel.NORTH) dock.add(iframe, DockPanel.CENTER) - + dock.setCellHorizontalAlignment(closeButton, HasAlignment.ALIGN_RIGHT) dock.setCellWidth(iframe, "100%") dock.setWidth("100%") iframe.setWidth("36em") iframe.setHeight("20em") self.setWidget(dock) - + # Work around for IE/MSHTML Issue 511 self.initURL = iframe.getUrl() self.iframe = iframe @@ -149,9 +149,9 @@ def onClick(self, sender): class MyPopup(PopupPanel): def __init__(self): PopupPanel.__init__(self, True) - + contents = HTML("Click anywhere outside this popup to make it disappear.") contents.setWidth("128px") self.setWidget(contents) - + self.setStyleName("ks-popups-Popup") diff --git a/examples/kitchensink/Tables.py b/examples/kitchensink/Tables.py index f2c0c608e..a0216f989 100644 --- a/examples/kitchensink/Tables.py +++ b/examples/kitchensink/Tables.py @@ -17,13 +17,13 @@ def __init__(self): outer.setHTML(1, 0, "Look to the right...
That's a nested table component ->") outer.setWidget(1, 1, inner) outer.getCellFormatter().setColSpan(1, 1, 2) - + for i in range(10): for j in range(5): inner.setText(i, j, "%d" % i + ",%d" % j) self.initWidget(outer) - + def onShow(self): pass diff --git a/examples/kitchensink/Tabs.py b/examples/kitchensink/Tabs.py index a29fc086d..aa69f5c9f 100644 --- a/examples/kitchensink/Tabs.py +++ b/examples/kitchensink/Tabs.py @@ -27,7 +27,7 @@ def onShow(self): def createImage(self, imageUrl): image = Image(imageUrl) image.setStyleName("ks-images-Image") - + p = VerticalPanel() p.setHorizontalAlignment(HasAlignment.ALIGN_CENTER) p.setVerticalAlignment(HasAlignment.ALIGN_MIDDLE) diff --git a/examples/kitchensink/Text.py b/examples/kitchensink/Text.py index 0624f3671..052cf8b48 100644 --- a/examples/kitchensink/Text.py +++ b/examples/kitchensink/Text.py @@ -24,7 +24,7 @@ def __init__(self): panel.add(self.createTextThing(self.fPasswordText)) panel.add(HTML("Text area:")) panel.add(self.createTextThing(self.fTextArea)) - + panel.add(HTML("""Textarea below demos oninput event. oninput allows to detect when the content of an element has changed. This is different from examples above, where changes are detected only if they are made with @@ -41,12 +41,12 @@ def __init__(self): vp.add(self.echo) textArea.addInputListener(self) panel.add(vp) - + self.initWidget(panel) def onShow(self): pass - + def onInput(self, sender): self.echo.setText(sender.getText()) @@ -60,7 +60,7 @@ def createTextThing(self, textBox): select_all = Button("select all") p.add(select_all) p.add(echo) - + listener=TextBoxListener(self, textBox, echo, select_all) select_all.addClickListener(listener) textBox.addKeyboardListener(listener) @@ -78,7 +78,7 @@ def __init__(self, parent, textBox, echo, select_all): self.echo=echo self.parent=parent self.select_all=select_all - + def onClick(self, sender): if sender == self.select_all: self.textBox.selectAll() @@ -91,11 +91,11 @@ def onKeyUp(self, sender, keyCode, modifiers): def onKeyDown(self, sender, keyCode, modifiers): pass - + def onKeyPress(self, sender, keyCode, modifiers): pass - + def init(): text="GWT includes the standard complement of text-entry widgets, each of which " text+="supports keyboard and selection events you can use to control text entry. " diff --git a/examples/kitchensink/Trees.py b/examples/kitchensink/Trees.py index 75242c905..2720df9db 100644 --- a/examples/kitchensink/Trees.py +++ b/examples/kitchensink/Trees.py @@ -8,34 +8,34 @@ def __init__(self): self.fProto = [ Proto("Beethoven", [ Proto("Concertos", [ - Proto("No. 1 - C"), - Proto("No. 2 - B-Flat Major"), - Proto("No. 3 - C Minor"), - Proto("No. 4 - G Major"), + Proto("No. 1 - C"), + Proto("No. 2 - B-Flat Major"), + Proto("No. 3 - C Minor"), + Proto("No. 4 - G Major"), Proto("No. 5 - E-Flat Major") ]), Proto("Quartets", [ - Proto("Six String Quartets"), - Proto("Three String Quartets"), + Proto("Six String Quartets"), + Proto("Three String Quartets"), Proto("Grosse Fugue for String Quartets") ]), Proto("Sonatas", [ - Proto("Sonata in A Minor"), + Proto("Sonata in A Minor"), Proto("Sonata in F Major") ]), Proto("Symphonies", [ - Proto("No. 1 - C Major"), - Proto("No. 2 - D Major"), - Proto("No. 3 - E-Flat Major"), - Proto("No. 4 - B-Flat Major"), - Proto("No. 5 - C Minor"), - Proto("No. 6 - F Major"), - Proto("No. 7 - A Major"), - Proto("No. 8 - F Major"), + Proto("No. 1 - C Major"), + Proto("No. 2 - D Major"), + Proto("No. 3 - E-Flat Major"), + Proto("No. 4 - B-Flat Major"), + Proto("No. 5 - C Minor"), + Proto("No. 6 - F Major"), + Proto("No. 7 - A Major"), + Proto("No. 8 - F Major"), Proto("No. 9 - D Minor") ]) ]), - + Proto("Brahms", [ Proto("Concertos", [ Proto("Violin Concerto"), @@ -58,9 +58,9 @@ def __init__(self): Proto("No. 2 - D Minor"), Proto("No. 3 - F Major"), Proto("No. 4 - E Minor") - ]) + ]) ]), - + Proto("Mozart", [ Proto("Concertos", [ Proto("Piano Concerto No. 12"), @@ -73,22 +73,22 @@ def __init__(self): ] self.fTree = Tree() - + for i in range(len(self.fProto)): self.createItem(self.fProto[i]) self.fTree.addItem(self.fProto[i].item) - + self.fTree.addTreeListener(self) self.initWidget(self.fTree) - + def onTreeItemSelected(self, item): pass - + def onTreeItemStateChanged(self, item): child = item.getChild(0) if hasattr(child, "isPendingItem"): item.removeItem(child) - + proto = item.getUserObject() for i in range(len(proto.children)): self.createItem(proto.children[i]) @@ -107,9 +107,9 @@ def getSortIndex(self, parent, text): break; else: node += 1 - + return node - + def createItem(self, proto): proto.item = TreeItem(proto.text) proto.item.setUserObject(proto) @@ -122,7 +122,7 @@ def __init__(self, text, children=None): self.children = [] self.item = None self.text = text - + if children is not None: self.children = children diff --git a/examples/libtest/ArgsTest.py b/examples/libtest/ArgsTest.py index 26e525624..db4f5dce0 100644 --- a/examples/libtest/ArgsTest.py +++ b/examples/libtest/ArgsTest.py @@ -1,941 +1,941 @@ -from UnitTest import UnitTest - -def aArgs(*args): - return args - -def ftest(a, b): - return [a, b] - -class ArgsTest(UnitTest): - - def testNaming1(self): - values = ftest(1, 2) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - - def testNaming2(self): - values = ftest(a=1, b=2) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - - def testNaming3(self): - values = ftest(1, b=2) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - - def testNaming4(self): - exc_raised = False - try: - values = ftest(1, c=2) - except TypeError, t: - exc_raised = True - self.assertTrue(exc_raised, "TypeError 'c' unexpected arg not raised") - - def testNaming5(self): - exc_raised = False - try: - values = ftest() - except TypeError, t: - exc_raised = True - self.assertTrue(exc_raised, "TypeError 'ftest() takes exactly 2 arguments (0 given)' not raised") - - def testSimpleCall(self): - values = foo(1, 2, 3) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = foo2(1, 2, 3) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - def testKeywordCall1(self): - values = foo2(c=3, b=2, a=1) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - def testKeywordCall2(self): - values = foo2(b=2, a=1, c=3) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - def testKeywordCall3(self): - values = foo2(1, c=3) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], None) - self.assertEquals(values[2], 3) - - def testKeywordCall4(self): - values = foo2() - self.assertEquals(values[0], None) - self.assertEquals(values[1], None) - self.assertEquals(values[2], None) - - def testKeywordCall5(self): - values = foo2(c=True) - self.assertEquals(values[0], None) - self.assertEquals(values[1], None) - self.assertEquals(values[2], True) - - def testStarArgs(self): - args = (1,2) - res = aArgs(*args) - self.assertEquals(args, res) - - args = "123" - try: - res = aArgs(*args) - called = True - exc = None - except TypeError, e: - called = False - exc = e - - # weird one: a string is a sequence, so it gets away with being - # called on its own as *args! eeugh. - self.assertTrue(called, - "exception not expected but function called:" + repr(res) + repr(exc)) - self.assertEquals(res, ("1", "2", "3")) - - - args = 1 - try: - res = aArgs(*args) - called = True - except TypeError: - called = False - - self.assertFalse(called, - "exception expected but not raised - TypeError: aArgs() argument after * must be a sequence") - - - args = (1,) - res = aArgs(*args) - self.assertEquals(args, res) - - args = (1,) - res = aArgs(args) - self.assertEquals((args,), res) - - - def testDefaultValuesCall(self): - values = foo3(b=7) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 7) - self.assertEquals(values[2], 3) - - values = foo3(a=9) - self.assertEquals(values[0], 9) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = foo3() - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - def testVarargsCall(self): - values = foo4(9, 8, 7, 2, 3, 4) - self.assertEquals(values[0], 9) - self.assertEquals(values[1], 8) - self.assertEquals(values[2], 7) - self.assertEquals(values[3][0], 2) - self.assertEquals(values[3][1], 3) - self.assertEquals(values[3][2], 4) - - values = foo4(9, 8, 7, 3, 2, 1) - self.assertEquals(values[0], 9) - self.assertEquals(values[1], 8) - self.assertEquals(values[2], 7) - self.assertEquals(values[3][0], 3) - self.assertEquals(values[3][1], 2) - self.assertEquals(values[3][2], 1) - - def testKwargsCall(self): - values = foo5(9, 8, 7, x=5, y=7) - self.assertEquals(values[0], 9) - self.assertEquals(values[1], 8) - self.assertEquals(values[2], 7) - self.assertEquals(values[3]["x"], 5) - self.assertEquals(values[3]["y"], 7) - - def testComboCall(self): - values = foo6(9, 8, 7, 1, 2, 3, x=4, y=5) - self.assertEquals(values[0], 9) - self.assertEquals(values[1], 8) - self.assertEquals(values[2], 7) - self.assertEquals(values[3][0], 1) - self.assertEquals(values[3][1], 2) - self.assertEquals(values[3][2], 3) - self.assertEquals(values[4]["x"], 4) - self.assertEquals(values[4]["y"], 5) - - def testEdgeCall(self): - values = foo7(1,2,3,b=2) - self.assertEqual(values[0], 1) - self.assertEqual(values[1], (2,3)) - self.assertEqual(values[2], {'b':2}) - - values = foo7(1, 2, 3, {'b':2}) - self.assertEqual(values[0], 1) - self.assertEqual(values[1], (2,3,{'b':2})) - self.assertEqual(values[2], {}) - - vaules = foo8(1, b=2) - self.assertEqual(vaules[0], 1) - self.assertEqual(vaules[1], {'b':2}) - - vaules = foo8({'b':2}) - self.assertEqual(vaules[0], {'b':2}) - self.assertEqual(vaules[1], {}) - - def testSimpleCtorCall(self): - values = ArgsTestClass_foo(1, 2, 3).x - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = ArgsTestClass_foo2(1, 2, 3).x - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - def testKeywordCtorCall(self): - values = ArgsTestClass_foo2(c=3, b=2, a=1).x - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = ArgsTestClass_foo2(b=2, a=1, c=3).x - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = ArgsTestClass_foo2().x - self.assertEquals(values[0], None) - self.assertEquals(values[1], None) - self.assertEquals(values[2], None) - - values = ArgsTestClass_foo2(c=True).x - self.assertEquals(values[0], None) - self.assertEquals(values[1], None) - self.assertEquals(values[2], True) - - - def testDefaultValuesCtorCall(self): - values = ArgsTestClass_foo3(b=7).x - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 7) - self.assertEquals(values[2], 3) - - values = ArgsTestClass_foo3(a=9).x - self.assertEquals(values[0], 9) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = ArgsTestClass_foo3().x - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - def testVarargsCtorCall(self): - values = ArgsTestClass_foo4(9, 8, 7, 2, 3, 4).x - self.assertEquals(values[0], 9) - self.assertEquals(values[1], 8) - self.assertEquals(values[2], 7) - self.assertEquals(values[3][0], 2) - self.assertEquals(values[3][1], 3) - self.assertEquals(values[3][2], 4) - - values = ArgsTestClass_foo4(9, 8, 7, 3, 2, 1).x - self.assertEquals(values[0], 9) - self.assertEquals(values[1], 8) - self.assertEquals(values[2], 7) - self.assertEquals(values[3][0], 3) - self.assertEquals(values[3][1], 2) - self.assertEquals(values[3][2], 1) - - def testKwargsCtorCall(self): - values = ArgsTestClass_foo5(9, 8, 7, x=5, y=7).x - self.assertEquals(values[0], 9) - self.assertEquals(values[1], 8) - self.assertEquals(values[2], 7) - self.assertEquals(values[3]["x"], 5) - self.assertEquals(values[3]["y"], 7) - - def testComboCtorCall(self): - values = ArgsTestClass_foo6(9, 8, 7, 1, 2, 3, x=4, y=5).x - self.assertEquals(values[0], 9) - self.assertEquals(values[1], 8) - self.assertEquals(values[2], 7) - self.assertEquals(values[3][0], 1) - self.assertEquals(values[3][1], 2) - self.assertEquals(values[3][2], 3) - self.assertEquals(values[4]["x"], 4) - self.assertEquals(values[4]["y"], 5) - - def testSimpleMethodCall(self): - values = ArgsTestClass().foo(1, 2, 3) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = ArgsTestClass().foo2(1, 2, 3) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - def testKeywordMethodCall(self): - values = ArgsTestClass().foo2(c=3, b=2, a=1) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = ArgsTestClass().foo2(b=2, a=1, c=3) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = ArgsTestClass().foo2() - self.assertEquals(values[0], None) - self.assertEquals(values[1], None) - self.assertEquals(values[2], None) - - values = ArgsTestClass().foo2(c=True) - self.assertEquals(values[0], None) - self.assertEquals(values[1], None) - self.assertEquals(values[2], True) - - - def testDefaultValuesMethodCall(self): - values = ArgsTestClass().foo3(b=7) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 7) - self.assertEquals(values[2], 3) - - values = ArgsTestClass().foo3(a=9) - self.assertEquals(values[0], 9) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = ArgsTestClass().foo3() - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - def testVarargsMethodCall(self): - values = ArgsTestClass().foo4(1, 2, 3) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = ArgsTestClass().foo4(3, 2, 1) - self.assertEquals(values[0], 3) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 1) - - def testKwargsMethodCall(self): - values = ArgsTestClass().foo5(x=5, y=7) - self.assertEquals(values["x"], 5) - self.assertEquals(values["y"], 7) - - def testComboMethodCall(self): - values = ArgsTestClass().foo6(1, 2, 3, x=4, y=5) - self.assertEquals(values[0][0], 1) - self.assertEquals(values[0][1], 2) - self.assertEquals(values[0][2], 3) - self.assertEquals(values[1]["x"], 4) - self.assertEquals(values[1]["y"], 5) - - def testEdgeMethodCall(self): - values = ArgsTestClass().foo7(1,2,3,b=2) - self.assertEqual(values[0], 1) - self.assertEqual(values[1], (2,3)) - self.assertEqual(values[2], {'b':2}) - - values = ArgsTestClass().foo7(1, 2, 3, {'b':2}) - self.assertEqual(values[0], 1) - self.assertEqual(values[1], (2,3,{'b':2})) - self.assertEqual(values[2], {}) - - vaules = ArgsTestClass().foo8(1, b=2) - self.assertEqual(vaules[0], 1) - self.assertEqual(vaules[1], {'b':2}) - - vaules = ArgsTestClass().foo8({'b':2}) - self.assertEqual(vaules[0], {'b':2}) - self.assertEqual(vaules[1], {}) - - def testSimpleStaticMethodCall(self): - values = ArgsTestClass2.foo(1, 2, 3) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = ArgsTestClass2.foo2(1, 2, 3) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - def testKeywordStaticMethodCall(self): - values = ArgsTestClass2.foo2(c=3, b=2, a=1) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = ArgsTestClass2.foo2(b=2, a=1, c=3) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = ArgsTestClass2.foo2() - self.assertEquals(values[0], None) - self.assertEquals(values[1], None) - self.assertEquals(values[2], None) - - values = ArgsTestClass2.foo2(c=True) - self.assertEquals(values[0], None) - self.assertEquals(values[1], None) - self.assertEquals(values[2], True) - - def testDefaultValuesStaticMethodCall(self): - values = ArgsTestClass2.foo3(b=7) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 7) - self.assertEquals(values[2], 3) - - values = ArgsTestClass2.foo3(a=9) - self.assertEquals(values[0], 9) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = ArgsTestClass2.foo3() - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - def testVarargsStaticMethodCall(self): - values = ArgsTestClass2.foo4(1, 2, 3) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = ArgsTestClass2.foo4(3, 2, 1) - self.assertEquals(values[0], 3) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 1) - - def testKwargsStaticMethodCall(self): - values = ArgsTestClass2.foo5(x=5, y=7) - self.assertEquals(values["x"], 5) - self.assertEquals(values["y"], 7) - - def testComboStaticMethodCall(self): - values = ArgsTestClass2.foo6(1, 2, 3, x=4, y=5) - self.assertEquals(values[0][0], 1) - self.assertEquals(values[0][1], 2) - self.assertEquals(values[0][2], 3) - self.assertEquals(values[1]["x"], 4) - self.assertEquals(values[1]["y"], 5) - - def testEdgeStaticMethodCall(self): - values = ArgsTestClass2.foo7(1,2,3,b=2) - self.assertEqual(values[0], 1) - self.assertEqual(values[1], (2,3)) - self.assertEqual(values[2], {'b':2}) - - values = ArgsTestClass2.foo7(1, 2, 3, {'b':2}) - self.assertEqual(values[0], 1) - self.assertEqual(values[1], (2,3,{'b':2})) - self.assertEqual(values[2], {}) - - vaules = ArgsTestClass2.foo8(1, b=2) - self.assertEqual(vaules[0], 1) - self.assertEqual(vaules[1], {'b':2}) - - vaules = ArgsTestClass2.foo8({'b':2}) - self.assertEqual(vaules[0], {'b':2}) - self.assertEqual(vaules[1], {}) - - def testSimpleClassMethodCall(self): - values = ArgsTestClass3.foo(1, 2, 3) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = ArgsTestClass3.foo2(1, 2, 3) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - def testKeywordClassMethodCall(self): - values = ArgsTestClass3.foo2(c=3, b=2, a=1) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = ArgsTestClass3.foo2(b=2, a=1, c=3) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = ArgsTestClass3.foo2() - self.assertEquals(values[0], None) - self.assertEquals(values[1], None) - self.assertEquals(values[2], None) - - values = ArgsTestClass3.foo2(c=True) - self.assertEquals(values[0], None) - self.assertEquals(values[1], None) - self.assertEquals(values[2], True) - - - def testDefaultValuesClassMethodCall(self): - values = ArgsTestClass3.foo3(b=7) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 7) - self.assertEquals(values[2], 3) - - values = ArgsTestClass3.foo3(a=9) - self.assertEquals(values[0], 9) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = ArgsTestClass3.foo3() - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - def testVarargsClassMethodCall(self): - values = ArgsTestClass3.foo4(1, 2, 3) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = ArgsTestClass3.foo4(3, 2, 1) - self.assertEquals(values[0], 3) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 1) - - def testKwargsClassMethodCall(self): - values = ArgsTestClass3.foo5(x=5, y=7) - self.assertEquals(values["x"], 5) - self.assertEquals(values["y"], 7) - - def testComboClassMethodCall(self): - values = ArgsTestClass3.foo6(1, 2, 3, x=4, y=5) - self.assertEquals(values[0][0], 1) - self.assertEquals(values[0][1], 2) - self.assertEquals(values[0][2], 3) - self.assertEquals(values[1]["x"], 4) - self.assertEquals(values[1]["y"], 5) - - def testEdgeClassMethodCall(self): - values = ArgsTestClass3.foo7(1,2,3,b=2) - self.assertEqual(values[0], 1) - self.assertEqual(values[1], (2,3)) - self.assertEqual(values[2], {'b':2}) - - values = ArgsTestClass3.foo7(1, 2, 3, {'b':2}) - self.assertEqual(values[0], 1) - self.assertEqual(values[1], (2,3,{'b':2})) - self.assertEqual(values[2], {}) - - vaules = ArgsTestClass3.foo8(1, b=2) - self.assertEqual(vaules[0], 1) - self.assertEqual(vaules[1], {'b':2}) - - vaules = ArgsTestClass3.foo8({'b':2}) - self.assertEqual(vaules[0], {'b':2}) - self.assertEqual(vaules[1], {}) - - def testSimpleIndirectClassMethodCall(self): - values = ArgsTestClass3().foo(1, 2, 3) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = ArgsTestClass3().foo2(1, 2, 3) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - def testKeywordIndirectClassMethodCall(self): - values = ArgsTestClass3().foo2(c=3, b=2, a=1) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = ArgsTestClass3().foo2(b=2, a=1, c=3) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = ArgsTestClass3().foo2() - self.assertEquals(values[0], None) - self.assertEquals(values[1], None) - self.assertEquals(values[2], None) - - values = ArgsTestClass3().foo2(c=True) - self.assertEquals(values[0], None) - self.assertEquals(values[1], None) - self.assertEquals(values[2], True) - - - def testDefaultValuesIndirectClassMethodCall(self): - values = ArgsTestClass3().foo3(b=7) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 7) - self.assertEquals(values[2], 3) - - values = ArgsTestClass3().foo3(a=9) - self.assertEquals(values[0], 9) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = ArgsTestClass3().foo3() - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - def testVarargsIndirectClassMethodCall(self): - values = ArgsTestClass3().foo4(1, 2, 3) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = ArgsTestClass3().foo4(3, 2, 1) - self.assertEquals(values[0], 3) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 1) - - def testKwargsIndirectClassMethodCall(self): - values = ArgsTestClass3().foo5(x=5, y=7) - self.assertEquals(values["x"], 5) - self.assertEquals(values["y"], 7) - - def testComboIndirectClassMethodCall(self): - values = ArgsTestClass3().foo6(1, 2, 3, x=4, y=5) - self.assertEquals(values[0][0], 1) - self.assertEquals(values[0][1], 2) - self.assertEquals(values[0][2], 3) - self.assertEquals(values[1]["x"], 4) - self.assertEquals(values[1]["y"], 5) - - def testKwArgsRecurse(self): - kwa = kw_args(x=5, y=6) - if kwa: - self.assertEquals(kwa.get('x'), 5) - self.assertEquals(kwa.get('y'), 6) - - kwa = kw_args2(x=5, y=6) - if kwa: - self.assertEquals(kwa.get('x'), 5) - self.assertEquals(kwa.get('y'), 6) - - values = varargs_kwargs(1,2,3,4,c=3) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], (3,4)) - self.assertEquals(values[3]['c'], 3) - - values = varargs_kwargs2(1,2,3,4,c=3) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], (3,4)) - self.assertEquals(values[3]['c'], 3) - - values = varargs_kwargs2(1) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 3) - - values = varargs_kwargs2(1, {'a':1}, {}) - self.assertEquals(values[0], 1) - self.assertEquals(values[1]['a'], 1) - - values = varargs_kwargs2(1, {'a':1}) - self.assertEquals(values[0], 1) - try: - self.assertEquals(values[1], {'a':1}) - except TypeError, e: - self.fail("Last arg in *args,**kwargs is dict problem") - - def testKwArgsInherit(self): - - c = KwArgs(x=5, y=6) - self.assertTrue(hasattr(c, 'kwargs')) - kwa = getattr(c, 'kwargs', None) - if kwa: - self.assertEquals(kwa.get('x'), 5) - self.assertEquals(kwa.get('y'), 6) - self.assertEquals(kwa.get('z'), 7) - - try: - c = Kwargs2(x=5, y=6) - self.assertTrue(hasattr(c, 'kwargs')) - kwa = getattr(c, 'kwargs', None) - if kwa: - self.assertEquals(kwa.get('x'), 5) - self.assertEquals(kwa.get('y'), 6) - self.assertEquals(kwa.get('z'), 7) - except: - self.assertTrue(False, "runtime error in kwargs, needs investigating") - - c.set_kwargs(x=5, y=6) - self.assertTrue(hasattr(c, 'kwargs')) - kwa = getattr(c, 'kwargs', None) - if kwa: - self.assertEquals(kwa.get('x'), 5) - self.assertEquals(kwa.get('y'), 6) - self.assertEquals(kwa.get('z'), 8) - - - c.set_kwargs2(x=5, y=6) - self.assertTrue(hasattr(c, 'kwargs')) - kwa = getattr(c, 'kwargs', None) - if kwa: - self.assertEquals(kwa.get('x'), 5) - self.assertEquals(kwa.get('y'), 6) - self.assertEquals(kwa.get('z'), 8) - - - c.set_kwargs3(x=5, y=6) - self.assertTrue(hasattr(c, 'kwargs')) - kwa = getattr(c, 'kwargs', None) - if kwa: - self.assertEquals(kwa.get('x'), 5) - self.assertEquals(kwa.get('y'), 6) - self.assertEquals(kwa.get('z'), 8) - - def testKwArgsNameMapping(self): - kwargs = dict(comment='Comment', name='Name') - def fn(comment=None, name=None): - return dict(comment=comment, name=name) - kwargs_out = fn(**kwargs) - self.assertEquals(kwargs, kwargs_out) - kwargs = {'comment': 'Comment', 'name': 'Name'} - kwargs_out = fn(**kwargs) - self.assertEquals(kwargs, kwargs_out) - - def testLookupOrder(self): - def fn(fint = int): - return fint(1.2); - class A: - def fn(self, fint = int): - return fint(1.2); - self.assertEqual(fn(), 1) - self.assertEqual(A().fn(), 1) - - def testArgIsModuleName(self): - def fn(ArgsTest): - return foo(ArgsTest, 2, 3) - self.assertEqual(__name__, 'ArgsTest', "Argument to fn must be equal to module name") - self.assertEqual(fn('foo'), ['foo', 2, 3]) - - def testGetattr(self): - instance = ArgsTestClass() - foo = instance.foo - - values = foo(1, 2, 3) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - values = foo(*(1, 2, 3)) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - - try: - values = foo(*(1, 2), **dict(c=3)) - self.assertEquals(values[0], 1) - self.assertEquals(values[1], 2) - self.assertEquals(values[2], 3) - except TypeError: - self.fail('foo() takes exactly 4 arguments (5 given), bug #503') - - def testArgsUnpack(self): - def func(a, (b, c), d): - return a + b + c + d - try: - self.assertEqual(func(1, (2, 3), 4), 10, 'Function args unpacking not supported, #527') - except: - self.fail('Bug #527 Function args unpacking not supported') - - -def foo(a, b, c): - return [a, b, c] - -def foo2(a=None, b=None, c=None): - return [a, b, c] - -def foo3(a=1, b=2, c=3): - return [a, b, c] - -def foo4(a, b, c, *args): - return a, b, c, args - -def foo5(a, b, c, **kwargs): - return a, b, c, kwargs - -def foo6(a, b, c, *args, **kwargs): - return (a, b, c, args, kwargs) - -def foo7(a, *args, **kwargs): - return (a, args, kwargs) - -def foo8(a, **kwargs): - return (a, kwargs) - -class ArgsTestClass_foo: - def __init__(self, a, b, c): - self.x = [a, b, c] - -class ArgsTestClass_foo2: - def __init__(self, a=None, b=None, c=None): - self.x = [a, b, c] - -class ArgsTestClass_foo3: - def __init__(self, a=1, b=2, c=3): - self.x = [a, b, c] - -class ArgsTestClass_foo4: - def __init__(self, a, b, c, *args): - self.x = a, b, c, args - -class ArgsTestClass_foo5: - def __init__(self, a, b, c, **kwargs): - self.x = a, b, c, kwargs - -class ArgsTestClass_foo6: - def __init__(self, a, b, c, *args, **kwargs): - self.x = (a, b, c, args, kwargs) - -class ArgsTestClass: - def foo(self, a, b, c): - return [a, b, c] - - def foo2(self, a=None, b=None, c=None): - return [a, b, c] - - def foo3(self, a=1, b=2, c=3): - return [a, b, c] - - def foo4(self, *args): - return args - - def foo5(self, **kwargs): - return kwargs - - def foo6(self, *args, **kwargs): - return (args, kwargs) - - def foo7(self, a, *args, **kwargs): - return (a, args, kwargs) - - def foo8(self, a, **kwargs): - return (a, kwargs) - - -class ArgsTestClass2: - @staticmethod - def foo(a, b, c): - return [a, b, c] - - @staticmethod - def foo2(a=None, b=None, c=None): - return [a, b, c] - - @staticmethod - def foo3(a=1, b=2, c=3): - return [a, b, c] - - @staticmethod - def foo4(*args): - return args - - @staticmethod - def foo5(**kwargs): - return kwargs - - @staticmethod - def foo6(*args, **kwargs): - return (args, kwargs) - - @staticmethod - def foo7(a, *args, **kwargs): - return (a, args, kwargs) - - @staticmethod - def foo8(a, **kwargs): - return (a, kwargs) - -class ArgsTestClass3: - @classmethod - def foo(self, a, b, c): - return [a, b, c] - - @classmethod - def foo2(self, a=None, b=None, c=None): - return [a, b, c] - - @classmethod - def foo3(self, a=1, b=2, c=3): - return [a, b, c] - - @classmethod - def foo4(self, *args): - return args - - @classmethod - def foo5(self, **kwargs): - return kwargs - - @classmethod - def foo6(self, *args, **kwargs): - return (args, kwargs) - - @classmethod - def foo7(self, a, *args, **kwargs): - return (a, args, kwargs) - - @classmethod - def foo8(self, a, **kwargs): - return (a, kwargs) - - -class KwArgs: - def __init__(self, z=7, zz=77, **kwargs): - self.kwargs = kwargs - self.kwargs['z'] = z # XXX this causes problems: kwargs is undefined - - def set_kwargs(self, z=8, **kwargs): - self.kwargs = kwargs - self.kwargs['z'] = z - -class Kwargs2(KwArgs): - - def __init__(self, **kwargs): - KwArgs.__init__(self, **kwargs) - - def set_kwargs2(self, **kwargs): - KwArgs.set_kwargs(self, **kwargs) - - def set_kwargs3(self, **kwargs): - skw = getattr(self, "set_kwargs") - skw(**kwargs) - -def kw_args(**kwargs): - return kwargs - -def kw_args2(**kwargs): - return kw_args(**kwargs) - -def varargs_kwargs(arg1, arg2=2, *args, **kwargs): - return (arg1, arg2, args, kwargs) - -def varargs_kwargs2(arg1, arg2=3, *args, **kwargs): - return varargs_kwargs(arg1, arg2, *args, **kwargs) +from UnitTest import UnitTest + +def aArgs(*args): + return args + +def ftest(a, b): + return [a, b] + +class ArgsTest(UnitTest): + + def testNaming1(self): + values = ftest(1, 2) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + + def testNaming2(self): + values = ftest(a=1, b=2) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + + def testNaming3(self): + values = ftest(1, b=2) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + + def testNaming4(self): + exc_raised = False + try: + values = ftest(1, c=2) + except TypeError, t: + exc_raised = True + self.assertTrue(exc_raised, "TypeError 'c' unexpected arg not raised") + + def testNaming5(self): + exc_raised = False + try: + values = ftest() + except TypeError, t: + exc_raised = True + self.assertTrue(exc_raised, "TypeError 'ftest() takes exactly 2 arguments (0 given)' not raised") + + def testSimpleCall(self): + values = foo(1, 2, 3) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = foo2(1, 2, 3) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + def testKeywordCall1(self): + values = foo2(c=3, b=2, a=1) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + def testKeywordCall2(self): + values = foo2(b=2, a=1, c=3) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + def testKeywordCall3(self): + values = foo2(1, c=3) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], None) + self.assertEquals(values[2], 3) + + def testKeywordCall4(self): + values = foo2() + self.assertEquals(values[0], None) + self.assertEquals(values[1], None) + self.assertEquals(values[2], None) + + def testKeywordCall5(self): + values = foo2(c=True) + self.assertEquals(values[0], None) + self.assertEquals(values[1], None) + self.assertEquals(values[2], True) + + def testStarArgs(self): + args = (1,2) + res = aArgs(*args) + self.assertEquals(args, res) + + args = "123" + try: + res = aArgs(*args) + called = True + exc = None + except TypeError, e: + called = False + exc = e + + # weird one: a string is a sequence, so it gets away with being + # called on its own as *args! eeugh. + self.assertTrue(called, + "exception not expected but function called:" + repr(res) + repr(exc)) + self.assertEquals(res, ("1", "2", "3")) + + + args = 1 + try: + res = aArgs(*args) + called = True + except TypeError: + called = False + + self.assertFalse(called, + "exception expected but not raised - TypeError: aArgs() argument after * must be a sequence") + + + args = (1,) + res = aArgs(*args) + self.assertEquals(args, res) + + args = (1,) + res = aArgs(args) + self.assertEquals((args,), res) + + + def testDefaultValuesCall(self): + values = foo3(b=7) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 7) + self.assertEquals(values[2], 3) + + values = foo3(a=9) + self.assertEquals(values[0], 9) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = foo3() + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + def testVarargsCall(self): + values = foo4(9, 8, 7, 2, 3, 4) + self.assertEquals(values[0], 9) + self.assertEquals(values[1], 8) + self.assertEquals(values[2], 7) + self.assertEquals(values[3][0], 2) + self.assertEquals(values[3][1], 3) + self.assertEquals(values[3][2], 4) + + values = foo4(9, 8, 7, 3, 2, 1) + self.assertEquals(values[0], 9) + self.assertEquals(values[1], 8) + self.assertEquals(values[2], 7) + self.assertEquals(values[3][0], 3) + self.assertEquals(values[3][1], 2) + self.assertEquals(values[3][2], 1) + + def testKwargsCall(self): + values = foo5(9, 8, 7, x=5, y=7) + self.assertEquals(values[0], 9) + self.assertEquals(values[1], 8) + self.assertEquals(values[2], 7) + self.assertEquals(values[3]["x"], 5) + self.assertEquals(values[3]["y"], 7) + + def testComboCall(self): + values = foo6(9, 8, 7, 1, 2, 3, x=4, y=5) + self.assertEquals(values[0], 9) + self.assertEquals(values[1], 8) + self.assertEquals(values[2], 7) + self.assertEquals(values[3][0], 1) + self.assertEquals(values[3][1], 2) + self.assertEquals(values[3][2], 3) + self.assertEquals(values[4]["x"], 4) + self.assertEquals(values[4]["y"], 5) + + def testEdgeCall(self): + values = foo7(1,2,3,b=2) + self.assertEqual(values[0], 1) + self.assertEqual(values[1], (2,3)) + self.assertEqual(values[2], {'b':2}) + + values = foo7(1, 2, 3, {'b':2}) + self.assertEqual(values[0], 1) + self.assertEqual(values[1], (2,3,{'b':2})) + self.assertEqual(values[2], {}) + + vaules = foo8(1, b=2) + self.assertEqual(vaules[0], 1) + self.assertEqual(vaules[1], {'b':2}) + + vaules = foo8({'b':2}) + self.assertEqual(vaules[0], {'b':2}) + self.assertEqual(vaules[1], {}) + + def testSimpleCtorCall(self): + values = ArgsTestClass_foo(1, 2, 3).x + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = ArgsTestClass_foo2(1, 2, 3).x + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + def testKeywordCtorCall(self): + values = ArgsTestClass_foo2(c=3, b=2, a=1).x + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = ArgsTestClass_foo2(b=2, a=1, c=3).x + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = ArgsTestClass_foo2().x + self.assertEquals(values[0], None) + self.assertEquals(values[1], None) + self.assertEquals(values[2], None) + + values = ArgsTestClass_foo2(c=True).x + self.assertEquals(values[0], None) + self.assertEquals(values[1], None) + self.assertEquals(values[2], True) + + + def testDefaultValuesCtorCall(self): + values = ArgsTestClass_foo3(b=7).x + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 7) + self.assertEquals(values[2], 3) + + values = ArgsTestClass_foo3(a=9).x + self.assertEquals(values[0], 9) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = ArgsTestClass_foo3().x + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + def testVarargsCtorCall(self): + values = ArgsTestClass_foo4(9, 8, 7, 2, 3, 4).x + self.assertEquals(values[0], 9) + self.assertEquals(values[1], 8) + self.assertEquals(values[2], 7) + self.assertEquals(values[3][0], 2) + self.assertEquals(values[3][1], 3) + self.assertEquals(values[3][2], 4) + + values = ArgsTestClass_foo4(9, 8, 7, 3, 2, 1).x + self.assertEquals(values[0], 9) + self.assertEquals(values[1], 8) + self.assertEquals(values[2], 7) + self.assertEquals(values[3][0], 3) + self.assertEquals(values[3][1], 2) + self.assertEquals(values[3][2], 1) + + def testKwargsCtorCall(self): + values = ArgsTestClass_foo5(9, 8, 7, x=5, y=7).x + self.assertEquals(values[0], 9) + self.assertEquals(values[1], 8) + self.assertEquals(values[2], 7) + self.assertEquals(values[3]["x"], 5) + self.assertEquals(values[3]["y"], 7) + + def testComboCtorCall(self): + values = ArgsTestClass_foo6(9, 8, 7, 1, 2, 3, x=4, y=5).x + self.assertEquals(values[0], 9) + self.assertEquals(values[1], 8) + self.assertEquals(values[2], 7) + self.assertEquals(values[3][0], 1) + self.assertEquals(values[3][1], 2) + self.assertEquals(values[3][2], 3) + self.assertEquals(values[4]["x"], 4) + self.assertEquals(values[4]["y"], 5) + + def testSimpleMethodCall(self): + values = ArgsTestClass().foo(1, 2, 3) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = ArgsTestClass().foo2(1, 2, 3) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + def testKeywordMethodCall(self): + values = ArgsTestClass().foo2(c=3, b=2, a=1) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = ArgsTestClass().foo2(b=2, a=1, c=3) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = ArgsTestClass().foo2() + self.assertEquals(values[0], None) + self.assertEquals(values[1], None) + self.assertEquals(values[2], None) + + values = ArgsTestClass().foo2(c=True) + self.assertEquals(values[0], None) + self.assertEquals(values[1], None) + self.assertEquals(values[2], True) + + + def testDefaultValuesMethodCall(self): + values = ArgsTestClass().foo3(b=7) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 7) + self.assertEquals(values[2], 3) + + values = ArgsTestClass().foo3(a=9) + self.assertEquals(values[0], 9) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = ArgsTestClass().foo3() + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + def testVarargsMethodCall(self): + values = ArgsTestClass().foo4(1, 2, 3) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = ArgsTestClass().foo4(3, 2, 1) + self.assertEquals(values[0], 3) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 1) + + def testKwargsMethodCall(self): + values = ArgsTestClass().foo5(x=5, y=7) + self.assertEquals(values["x"], 5) + self.assertEquals(values["y"], 7) + + def testComboMethodCall(self): + values = ArgsTestClass().foo6(1, 2, 3, x=4, y=5) + self.assertEquals(values[0][0], 1) + self.assertEquals(values[0][1], 2) + self.assertEquals(values[0][2], 3) + self.assertEquals(values[1]["x"], 4) + self.assertEquals(values[1]["y"], 5) + + def testEdgeMethodCall(self): + values = ArgsTestClass().foo7(1,2,3,b=2) + self.assertEqual(values[0], 1) + self.assertEqual(values[1], (2,3)) + self.assertEqual(values[2], {'b':2}) + + values = ArgsTestClass().foo7(1, 2, 3, {'b':2}) + self.assertEqual(values[0], 1) + self.assertEqual(values[1], (2,3,{'b':2})) + self.assertEqual(values[2], {}) + + vaules = ArgsTestClass().foo8(1, b=2) + self.assertEqual(vaules[0], 1) + self.assertEqual(vaules[1], {'b':2}) + + vaules = ArgsTestClass().foo8({'b':2}) + self.assertEqual(vaules[0], {'b':2}) + self.assertEqual(vaules[1], {}) + + def testSimpleStaticMethodCall(self): + values = ArgsTestClass2.foo(1, 2, 3) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = ArgsTestClass2.foo2(1, 2, 3) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + def testKeywordStaticMethodCall(self): + values = ArgsTestClass2.foo2(c=3, b=2, a=1) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = ArgsTestClass2.foo2(b=2, a=1, c=3) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = ArgsTestClass2.foo2() + self.assertEquals(values[0], None) + self.assertEquals(values[1], None) + self.assertEquals(values[2], None) + + values = ArgsTestClass2.foo2(c=True) + self.assertEquals(values[0], None) + self.assertEquals(values[1], None) + self.assertEquals(values[2], True) + + def testDefaultValuesStaticMethodCall(self): + values = ArgsTestClass2.foo3(b=7) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 7) + self.assertEquals(values[2], 3) + + values = ArgsTestClass2.foo3(a=9) + self.assertEquals(values[0], 9) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = ArgsTestClass2.foo3() + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + def testVarargsStaticMethodCall(self): + values = ArgsTestClass2.foo4(1, 2, 3) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = ArgsTestClass2.foo4(3, 2, 1) + self.assertEquals(values[0], 3) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 1) + + def testKwargsStaticMethodCall(self): + values = ArgsTestClass2.foo5(x=5, y=7) + self.assertEquals(values["x"], 5) + self.assertEquals(values["y"], 7) + + def testComboStaticMethodCall(self): + values = ArgsTestClass2.foo6(1, 2, 3, x=4, y=5) + self.assertEquals(values[0][0], 1) + self.assertEquals(values[0][1], 2) + self.assertEquals(values[0][2], 3) + self.assertEquals(values[1]["x"], 4) + self.assertEquals(values[1]["y"], 5) + + def testEdgeStaticMethodCall(self): + values = ArgsTestClass2.foo7(1,2,3,b=2) + self.assertEqual(values[0], 1) + self.assertEqual(values[1], (2,3)) + self.assertEqual(values[2], {'b':2}) + + values = ArgsTestClass2.foo7(1, 2, 3, {'b':2}) + self.assertEqual(values[0], 1) + self.assertEqual(values[1], (2,3,{'b':2})) + self.assertEqual(values[2], {}) + + vaules = ArgsTestClass2.foo8(1, b=2) + self.assertEqual(vaules[0], 1) + self.assertEqual(vaules[1], {'b':2}) + + vaules = ArgsTestClass2.foo8({'b':2}) + self.assertEqual(vaules[0], {'b':2}) + self.assertEqual(vaules[1], {}) + + def testSimpleClassMethodCall(self): + values = ArgsTestClass3.foo(1, 2, 3) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = ArgsTestClass3.foo2(1, 2, 3) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + def testKeywordClassMethodCall(self): + values = ArgsTestClass3.foo2(c=3, b=2, a=1) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = ArgsTestClass3.foo2(b=2, a=1, c=3) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = ArgsTestClass3.foo2() + self.assertEquals(values[0], None) + self.assertEquals(values[1], None) + self.assertEquals(values[2], None) + + values = ArgsTestClass3.foo2(c=True) + self.assertEquals(values[0], None) + self.assertEquals(values[1], None) + self.assertEquals(values[2], True) + + + def testDefaultValuesClassMethodCall(self): + values = ArgsTestClass3.foo3(b=7) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 7) + self.assertEquals(values[2], 3) + + values = ArgsTestClass3.foo3(a=9) + self.assertEquals(values[0], 9) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = ArgsTestClass3.foo3() + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + def testVarargsClassMethodCall(self): + values = ArgsTestClass3.foo4(1, 2, 3) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = ArgsTestClass3.foo4(3, 2, 1) + self.assertEquals(values[0], 3) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 1) + + def testKwargsClassMethodCall(self): + values = ArgsTestClass3.foo5(x=5, y=7) + self.assertEquals(values["x"], 5) + self.assertEquals(values["y"], 7) + + def testComboClassMethodCall(self): + values = ArgsTestClass3.foo6(1, 2, 3, x=4, y=5) + self.assertEquals(values[0][0], 1) + self.assertEquals(values[0][1], 2) + self.assertEquals(values[0][2], 3) + self.assertEquals(values[1]["x"], 4) + self.assertEquals(values[1]["y"], 5) + + def testEdgeClassMethodCall(self): + values = ArgsTestClass3.foo7(1,2,3,b=2) + self.assertEqual(values[0], 1) + self.assertEqual(values[1], (2,3)) + self.assertEqual(values[2], {'b':2}) + + values = ArgsTestClass3.foo7(1, 2, 3, {'b':2}) + self.assertEqual(values[0], 1) + self.assertEqual(values[1], (2,3,{'b':2})) + self.assertEqual(values[2], {}) + + vaules = ArgsTestClass3.foo8(1, b=2) + self.assertEqual(vaules[0], 1) + self.assertEqual(vaules[1], {'b':2}) + + vaules = ArgsTestClass3.foo8({'b':2}) + self.assertEqual(vaules[0], {'b':2}) + self.assertEqual(vaules[1], {}) + + def testSimpleIndirectClassMethodCall(self): + values = ArgsTestClass3().foo(1, 2, 3) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = ArgsTestClass3().foo2(1, 2, 3) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + def testKeywordIndirectClassMethodCall(self): + values = ArgsTestClass3().foo2(c=3, b=2, a=1) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = ArgsTestClass3().foo2(b=2, a=1, c=3) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = ArgsTestClass3().foo2() + self.assertEquals(values[0], None) + self.assertEquals(values[1], None) + self.assertEquals(values[2], None) + + values = ArgsTestClass3().foo2(c=True) + self.assertEquals(values[0], None) + self.assertEquals(values[1], None) + self.assertEquals(values[2], True) + + + def testDefaultValuesIndirectClassMethodCall(self): + values = ArgsTestClass3().foo3(b=7) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 7) + self.assertEquals(values[2], 3) + + values = ArgsTestClass3().foo3(a=9) + self.assertEquals(values[0], 9) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = ArgsTestClass3().foo3() + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + def testVarargsIndirectClassMethodCall(self): + values = ArgsTestClass3().foo4(1, 2, 3) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = ArgsTestClass3().foo4(3, 2, 1) + self.assertEquals(values[0], 3) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 1) + + def testKwargsIndirectClassMethodCall(self): + values = ArgsTestClass3().foo5(x=5, y=7) + self.assertEquals(values["x"], 5) + self.assertEquals(values["y"], 7) + + def testComboIndirectClassMethodCall(self): + values = ArgsTestClass3().foo6(1, 2, 3, x=4, y=5) + self.assertEquals(values[0][0], 1) + self.assertEquals(values[0][1], 2) + self.assertEquals(values[0][2], 3) + self.assertEquals(values[1]["x"], 4) + self.assertEquals(values[1]["y"], 5) + + def testKwArgsRecurse(self): + kwa = kw_args(x=5, y=6) + if kwa: + self.assertEquals(kwa.get('x'), 5) + self.assertEquals(kwa.get('y'), 6) + + kwa = kw_args2(x=5, y=6) + if kwa: + self.assertEquals(kwa.get('x'), 5) + self.assertEquals(kwa.get('y'), 6) + + values = varargs_kwargs(1,2,3,4,c=3) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], (3,4)) + self.assertEquals(values[3]['c'], 3) + + values = varargs_kwargs2(1,2,3,4,c=3) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], (3,4)) + self.assertEquals(values[3]['c'], 3) + + values = varargs_kwargs2(1) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 3) + + values = varargs_kwargs2(1, {'a':1}, {}) + self.assertEquals(values[0], 1) + self.assertEquals(values[1]['a'], 1) + + values = varargs_kwargs2(1, {'a':1}) + self.assertEquals(values[0], 1) + try: + self.assertEquals(values[1], {'a':1}) + except TypeError, e: + self.fail("Last arg in *args,**kwargs is dict problem") + + def testKwArgsInherit(self): + + c = KwArgs(x=5, y=6) + self.assertTrue(hasattr(c, 'kwargs')) + kwa = getattr(c, 'kwargs', None) + if kwa: + self.assertEquals(kwa.get('x'), 5) + self.assertEquals(kwa.get('y'), 6) + self.assertEquals(kwa.get('z'), 7) + + try: + c = Kwargs2(x=5, y=6) + self.assertTrue(hasattr(c, 'kwargs')) + kwa = getattr(c, 'kwargs', None) + if kwa: + self.assertEquals(kwa.get('x'), 5) + self.assertEquals(kwa.get('y'), 6) + self.assertEquals(kwa.get('z'), 7) + except: + self.assertTrue(False, "runtime error in kwargs, needs investigating") + + c.set_kwargs(x=5, y=6) + self.assertTrue(hasattr(c, 'kwargs')) + kwa = getattr(c, 'kwargs', None) + if kwa: + self.assertEquals(kwa.get('x'), 5) + self.assertEquals(kwa.get('y'), 6) + self.assertEquals(kwa.get('z'), 8) + + + c.set_kwargs2(x=5, y=6) + self.assertTrue(hasattr(c, 'kwargs')) + kwa = getattr(c, 'kwargs', None) + if kwa: + self.assertEquals(kwa.get('x'), 5) + self.assertEquals(kwa.get('y'), 6) + self.assertEquals(kwa.get('z'), 8) + + + c.set_kwargs3(x=5, y=6) + self.assertTrue(hasattr(c, 'kwargs')) + kwa = getattr(c, 'kwargs', None) + if kwa: + self.assertEquals(kwa.get('x'), 5) + self.assertEquals(kwa.get('y'), 6) + self.assertEquals(kwa.get('z'), 8) + + def testKwArgsNameMapping(self): + kwargs = dict(comment='Comment', name='Name') + def fn(comment=None, name=None): + return dict(comment=comment, name=name) + kwargs_out = fn(**kwargs) + self.assertEquals(kwargs, kwargs_out) + kwargs = {'comment': 'Comment', 'name': 'Name'} + kwargs_out = fn(**kwargs) + self.assertEquals(kwargs, kwargs_out) + + def testLookupOrder(self): + def fn(fint = int): + return fint(1.2); + class A: + def fn(self, fint = int): + return fint(1.2); + self.assertEqual(fn(), 1) + self.assertEqual(A().fn(), 1) + + def testArgIsModuleName(self): + def fn(ArgsTest): + return foo(ArgsTest, 2, 3) + self.assertEqual(__name__, 'ArgsTest', "Argument to fn must be equal to module name") + self.assertEqual(fn('foo'), ['foo', 2, 3]) + + def testGetattr(self): + instance = ArgsTestClass() + foo = instance.foo + + values = foo(1, 2, 3) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + values = foo(*(1, 2, 3)) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + + try: + values = foo(*(1, 2), **dict(c=3)) + self.assertEquals(values[0], 1) + self.assertEquals(values[1], 2) + self.assertEquals(values[2], 3) + except TypeError: + self.fail('foo() takes exactly 4 arguments (5 given), bug #503') + + def testArgsUnpack(self): + def func(a, (b, c), d): + return a + b + c + d + try: + self.assertEqual(func(1, (2, 3), 4), 10, 'Function args unpacking not supported, #527') + except: + self.fail('Bug #527 Function args unpacking not supported') + + +def foo(a, b, c): + return [a, b, c] + +def foo2(a=None, b=None, c=None): + return [a, b, c] + +def foo3(a=1, b=2, c=3): + return [a, b, c] + +def foo4(a, b, c, *args): + return a, b, c, args + +def foo5(a, b, c, **kwargs): + return a, b, c, kwargs + +def foo6(a, b, c, *args, **kwargs): + return (a, b, c, args, kwargs) + +def foo7(a, *args, **kwargs): + return (a, args, kwargs) + +def foo8(a, **kwargs): + return (a, kwargs) + +class ArgsTestClass_foo: + def __init__(self, a, b, c): + self.x = [a, b, c] + +class ArgsTestClass_foo2: + def __init__(self, a=None, b=None, c=None): + self.x = [a, b, c] + +class ArgsTestClass_foo3: + def __init__(self, a=1, b=2, c=3): + self.x = [a, b, c] + +class ArgsTestClass_foo4: + def __init__(self, a, b, c, *args): + self.x = a, b, c, args + +class ArgsTestClass_foo5: + def __init__(self, a, b, c, **kwargs): + self.x = a, b, c, kwargs + +class ArgsTestClass_foo6: + def __init__(self, a, b, c, *args, **kwargs): + self.x = (a, b, c, args, kwargs) + +class ArgsTestClass: + def foo(self, a, b, c): + return [a, b, c] + + def foo2(self, a=None, b=None, c=None): + return [a, b, c] + + def foo3(self, a=1, b=2, c=3): + return [a, b, c] + + def foo4(self, *args): + return args + + def foo5(self, **kwargs): + return kwargs + + def foo6(self, *args, **kwargs): + return (args, kwargs) + + def foo7(self, a, *args, **kwargs): + return (a, args, kwargs) + + def foo8(self, a, **kwargs): + return (a, kwargs) + + +class ArgsTestClass2: + @staticmethod + def foo(a, b, c): + return [a, b, c] + + @staticmethod + def foo2(a=None, b=None, c=None): + return [a, b, c] + + @staticmethod + def foo3(a=1, b=2, c=3): + return [a, b, c] + + @staticmethod + def foo4(*args): + return args + + @staticmethod + def foo5(**kwargs): + return kwargs + + @staticmethod + def foo6(*args, **kwargs): + return (args, kwargs) + + @staticmethod + def foo7(a, *args, **kwargs): + return (a, args, kwargs) + + @staticmethod + def foo8(a, **kwargs): + return (a, kwargs) + +class ArgsTestClass3: + @classmethod + def foo(self, a, b, c): + return [a, b, c] + + @classmethod + def foo2(self, a=None, b=None, c=None): + return [a, b, c] + + @classmethod + def foo3(self, a=1, b=2, c=3): + return [a, b, c] + + @classmethod + def foo4(self, *args): + return args + + @classmethod + def foo5(self, **kwargs): + return kwargs + + @classmethod + def foo6(self, *args, **kwargs): + return (args, kwargs) + + @classmethod + def foo7(self, a, *args, **kwargs): + return (a, args, kwargs) + + @classmethod + def foo8(self, a, **kwargs): + return (a, kwargs) + + +class KwArgs: + def __init__(self, z=7, zz=77, **kwargs): + self.kwargs = kwargs + self.kwargs['z'] = z # XXX this causes problems: kwargs is undefined + + def set_kwargs(self, z=8, **kwargs): + self.kwargs = kwargs + self.kwargs['z'] = z + +class Kwargs2(KwArgs): + + def __init__(self, **kwargs): + KwArgs.__init__(self, **kwargs) + + def set_kwargs2(self, **kwargs): + KwArgs.set_kwargs(self, **kwargs) + + def set_kwargs3(self, **kwargs): + skw = getattr(self, "set_kwargs") + skw(**kwargs) + +def kw_args(**kwargs): + return kwargs + +def kw_args2(**kwargs): + return kw_args(**kwargs) + +def varargs_kwargs(arg1, arg2=2, *args, **kwargs): + return (arg1, arg2, args, kwargs) + +def varargs_kwargs2(arg1, arg2=3, *args, **kwargs): + return varargs_kwargs(arg1, arg2, *args, **kwargs) diff --git a/examples/libtest/AttributeTest.py b/examples/libtest/AttributeTest.py index 151137067..4b301a550 100644 --- a/examples/libtest/AttributeTest.py +++ b/examples/libtest/AttributeTest.py @@ -35,16 +35,16 @@ def delete_me(self): class AttributeTest(UnitTest): def testHasattr(self): - self.assertEqual(hasattr(self, "getName"), True, + self.assertEqual(hasattr(self, "getName"), True, "AttrTest should have method 'getName'") - self.assertEqual(hasattr(self, "blah"), False, + self.assertEqual(hasattr(self, "blah"), False, "AttrTest has no method 'getName'") - self.assertEqual(hasattr("", "find"), True, + self.assertEqual(hasattr("", "find"), True, "str should have method 'find', bug #483") - self.assertEqual(hasattr(1.0, "real"), True, + self.assertEqual(hasattr(1.0, "real"), True, "float should have attribute 'real', bug #483") - self.assertEqual(hasattr(1, "real"), True, - "int should have attribute 'real', bug #483") + self.assertEqual(hasattr(1, "real"), True, + "int should have attribute 'real', bug #483") def testGetattr(self): @@ -95,7 +95,7 @@ def testDelAttr(self): self.assertEqual(hasattr(foo, "v"), True) delattr(foo, "v") self.assertEqual(hasattr(foo, "v"), False) - + self.assertEqual(hasattr(foo, "getV"), True) try: delattr(foo, "getV") @@ -182,7 +182,7 @@ def testAttributMapping(self): self.assertTrue(hasattr(Foo, 'typeof')) del Foo.typeof self.assertFalse(hasattr(Foo, 'typeof')) - + def testTypeAttributes(self): try: x = [].append @@ -197,16 +197,16 @@ def testTypeAttributes(self): x = "asdfgd".rjust except Exception, e: self.fail("String attribute, #595, '%s'" % e) - + def testExpressionAttributeCall(self): s1 = " 1234" s2 = "5678 " - + def s3(): return " 6 " - + l = [" 1 ", " 2", "3 "] - + self.assertEqual((s1 + s2).strip(), "12345678") self.assertEqual((s1 + "").strip(), "1234") self.assertEqual(l[0].strip(), "1") diff --git a/examples/libtest/Base64ModuleTest.py b/examples/libtest/Base64ModuleTest.py index c5391d677..8f23ce3e2 100644 --- a/examples/libtest/Base64ModuleTest.py +++ b/examples/libtest/Base64ModuleTest.py @@ -32,7 +32,7 @@ def testBase64(self): def testBase32(self): text = "Pyjamas is fun" - + encodetext = base64.b32encode(text) self.assertEqual(encodetext, 'KB4WUYLNMFZSA2LTEBTHK3Q=') decodetext = base64.b32decode(encodetext) @@ -40,7 +40,7 @@ def testBase32(self): def testBase16(self): text = "Pyjamas is fun" - + encodetext = base64.b16encode(text) self.assertEqual(encodetext, '50796A616D61732069732066756E') decodetext = base64.b16decode(encodetext) diff --git a/examples/libtest/BoolTest.py b/examples/libtest/BoolTest.py index 88ffad469..30f9538bb 100644 --- a/examples/libtest/BoolTest.py +++ b/examples/libtest/BoolTest.py @@ -143,7 +143,7 @@ def testWhileStatement(self): self.fail("None-empty lists should evaluate to True in While") def testLogic(self): - + x = 0 or None self.assertEqual(x, None, "0 or None should be None not %s" % repr(x) ) @@ -211,7 +211,7 @@ def testLogic(self): self.assertTrue(tst, "#297 -non-empty object or {} should return the object") except TypeError: self.fail("#297 TypeError should not have been thrown") - + d = {} d2 = d or 5 diff --git a/examples/libtest/BuiltinTest.py b/examples/libtest/BuiltinTest.py index 3c9a6894a..d399748d1 100644 --- a/examples/libtest/BuiltinTest.py +++ b/examples/libtest/BuiltinTest.py @@ -290,11 +290,11 @@ def testImport(self): self.assertTrue(CLS is imports.loccls.CLS, "CLS is imports.loccls.CLS") self.assertTrue(CLS is imports.upcls.CLS, "CLS is imports.upcls.CLS") - def testImport(self): + def testImport(self): self.fail("Bug #XXX - from X import .. not completely implemented, only considering modules") return - + from imports import __doc__ as imports_doc self.assertEqual(imports.__doc__, imports_doc, "Module object must have __doc__ attribute") from imports import __name__ as imports_name @@ -306,12 +306,12 @@ def testImport(self): self.assertEqual(imports.all_import1, 1) self.assertEqual(imports.all_import2, 3) self.assertEqual(imports.all_import3, 3) - - + + # import builtins module import __builtin__ self.assertEqual(__builtin__.dict, dict, "__builtin__.dict != dict") - + from __builtin__ import dict as dict_bltin self.assertEqual(dict_bltin, dict, "__builtin__.dict != dict") @@ -486,7 +486,7 @@ def testForLoop(self): e = 2 self.assertEqual(i, 0) self.assertEqual(e, 1) - + class X(object): pass x = X() @@ -494,27 +494,27 @@ class X(object): for x.a in [3,4,5]: pass self.assertEqual(x.a, 5) - + d = {} for d['zz'] in [1,2,3]: pass self.assertEqual(d, {'zz': 3}) - + l = [1] for l[0] in [1,2,3]: pass self.assertEqual(l, [3]) - + l = [1,3,4] for l[1:2] in [[5,6,7]]: pass self.assertEqual(l, [1, 5, 6, 7, 4]) - + x = ((1, 2), 3, (4, 5)) for (a, b), c, (d, e) in [x]*5: pass self.assertEqual([a, b, c, d, e], [1,2,3,4,5]) - + for [[a, b], c, [d, e]] in [x]*5: pass self.assertEqual([a, b, c, d, e], [1,2,3,4,5]) @@ -745,7 +745,7 @@ def __format__(self, format_spec): if format_spec == 'd': return 'G(' + self.x + ')' return object.__format__(self, format_spec) - + class Galt: def __init__(self, x): self.x = x diff --git a/examples/libtest/ClassTest.py b/examples/libtest/ClassTest.py index 218b9b8f6..71cf45c04 100644 --- a/examples/libtest/ClassTest.py +++ b/examples/libtest/ClassTest.py @@ -33,7 +33,7 @@ class GetAttribute(): class Sink: def __init__(self): self.sink = "Sink" - + class SinkInfo: def __init__(self, object_type): self.object_type=object_type @@ -46,7 +46,7 @@ def getInstance(self): if self.instance==None: self.instance=self.createInstance() return self.instance - + class Trees(Sink): def __init__(self): Sink.__init__(self) @@ -359,7 +359,7 @@ def testInheritedConstructors(self): self.assertEqual(ExampleChildConstructor.z, expected_result3, "Did not inherit class var from grandparent") self.assertEqual(ExampleChildNoConstructor.z, expected_result3, "Did not inherit class var from grandparent") self.assertEqual(ExampleChildExplicitConstructor.z, expected_result3, "Did not inherit class var from grandparent") - + def testInheritFromType(self): i_types = [(int, 1), (float, 1.5), (str, "test"), (long, 1), @@ -375,10 +375,10 @@ def test_inh_method(self): self.assertEqual(inst.test_inh_method(), 1, "Methods of subclasses of type '%s' fail, issue #623" % cls.__name__) self.assertEqual(str(inst), str(val), "__str__ of subclasses of type '%s' fail, issue #623" % cls.__name__) self.assertEqual(type(inst), subclassed_type, "Subclasses of type '%s' have wrong type, issue #623" % cls.__name__) - self.assertTrue(isinstance(inst, subclassed_type), "Subclasses of type '%s' have wrong type, issue #623" % cls.__name__) + self.assertTrue(isinstance(inst, subclassed_type), "Subclasses of type '%s' have wrong type, issue #623" % cls.__name__) except: self.fail("Subclassing type '%s' does not work, issue #623" % cls.__name__) - + class SubclassedString(str): pass class SubclassedInt(int): pass @@ -568,24 +568,24 @@ def testInstanceChecking(self): self.fail('Failed to raise error for invalid instance') except TypeError, e: self.assertTrue(e.args[0].find('get_x() must be called') >= 0, e.args[0]) - + def testIsSubclass(self): class A: pass class B(A): pass class C(B): pass class D: pass class E(D, C): pass - + self.assertTrue(issubclass(A, A)) self.assertTrue(issubclass(C, A)) self.assertTrue(issubclass(E, A)) self.assertTrue(issubclass(E, (PassMeAClass, A))) self.assertFalse(issubclass(A, PassMeAClass)) - + self.assertRaises(TypeError, issubclass, PassMeAClass(), PassMeAClass) self.assertRaises(TypeError, issubclass, PassMeAClass, PassMeAClass()) self.assertRaises(TypeError, issubclass, None, PassMeAClass) - + def testMetaClass(self): Klass = type('MyClass', (object,), {'method': method, 'x': 5}) instance = Klass() @@ -763,7 +763,7 @@ def testGlobalClassFactory(self): self.assertEqual(pmc.foo(), "foo in PassMeAClass", "foo !in PassMeAClass") try: - pmc = ggetObject("mscp1", 5) + pmc = ggetObject("mscp1", 5) except: self.assertEqual(False, True, "Exception indicates bug in compiler: 'Error: uncaught exception: ExampleMultiSuperclassParent1() arguments after ** must be a dictionary 5'") else: @@ -922,7 +922,7 @@ class B(object): def __init__(self): self.v = 1 self.b = B() - + a = A(0) self.assertEqual(a.b.v, 0) a = A(1) @@ -1014,18 +1014,18 @@ def m2(self): class T(cl[0]): pass self.assertEqual(T([1]), [1]) - + class T(cl[1], cl[2]): pass t = T() self.assertEqual(t.m1(), 1) self.assertEqual(t.m2(), 2) - + class T2(type(t)): pass t2 = T2() self.assertEqual(t2.m1(), 1) - self.assertEqual(t2.m2(), 2) + self.assertEqual(t2.m2(), 2) class PassMeAClass(object): def __init__(self): @@ -1035,7 +1035,7 @@ def foo(self): def PassMeAClassFunction(klass): c = klass() - return c.foo() + return c.foo() # testMetaClass def method(self): @@ -1064,10 +1064,10 @@ def sampleClassMethodKwargs(cls, a=0, b=1, c=2): @staticmethod def sampleStaticMethod(arg): return arg - + def shouldntWork(arg): return "before" + arg + "after" - + oldIdiomStaticMethod = staticmethod(shouldntWork) def fail_a(self): @@ -1167,7 +1167,7 @@ def __new__(cls): return ObjectClass.__new__(cls) def __init__(self): self.init = True - + class OtherClass3(object): def __new__(cls, x, y): val = object.__new__(cls) diff --git a/examples/libtest/CompileTest.py b/examples/libtest/CompileTest.py index 61e6ec9c3..25f0f8baf 100644 --- a/examples/libtest/CompileTest.py +++ b/examples/libtest/CompileTest.py @@ -12,7 +12,7 @@ def test_issue_432(self): #issue 432 x, y = 1, 2 del x, y - + def test_issue_433(self): #issue 433 for x in [1, 2] + [3, 4]: @@ -24,13 +24,13 @@ def test_discard_expressions(self): x "some string" #self.fail("ast.Discard nodes, #584") - + def test_callfunc_expressions(self): s = "123" x = ('a' + 'b').strip() (" " + s).rstrip() #self.fail("Callfunc over expressions, #591") - + def test_function_deep_args_unpacking(self): """ def func(a, (b, (c, d)), e): @@ -52,7 +52,7 @@ def test_bad_import(self): try: import _importtimeerror except: pass - + """ try: import _badsyntaxmodule except: pass @@ -74,7 +74,7 @@ class X: pass """ self.fail("try/catch in class definition scope, issue #593") - + def testWithFlowControl(self): # Hard to make work correctly! # Should walk ast and track them @@ -84,9 +84,9 @@ def return_stmt(): with self.Dummy(): if i == 2: return i - + self.assertEqual(return_stmt(), 2) - + def break_stmt(): x = 0 for i in range(10): @@ -95,7 +95,7 @@ def break_stmt(): if i == 2: break return x - + self.assertEqual(break_stmt(), 2) def continue_stmt(): @@ -106,8 +106,8 @@ def continue_stmt(): continue x += 100 return x - + self.assertEqual(continue_stmt(), 10) """ self.fail("Flow control statements inside with, issue #625") - + diff --git a/examples/libtest/CsvModuleTest.py b/examples/libtest/CsvModuleTest.py index 404833044..18baeee11 100644 --- a/examples/libtest/CsvModuleTest.py +++ b/examples/libtest/CsvModuleTest.py @@ -22,15 +22,15 @@ def test_reader(self): '', ] expected = [ - ['1', ' 2', '3'], - [' "s"', 'a', 'as,2'], - [' "s', 'a ', 'as,2'], - ['s', ' "a" ', 'as,\n2'], - [' ""s', ' "a" ', 'as,2'], - [], - [], - ['1', ' 2', '3'], - ['s', ' "a" ', 'as,\n2'], + ['1', ' 2', '3'], + [' "s"', 'a', 'as,2'], + [' "s', 'a ', 'as,2'], + ['s', ' "a" ', 'as,\n2'], + [' ""s', ' "a" ', 'as,2'], + [], + [], + ['1', ' 2', '3'], + ['s', ' "a" ', 'as,\n2'], [], ] reader = csv.reader(lines) @@ -38,7 +38,7 @@ def test_reader(self): idx = -1 for row in reader: idx += 1 - self.assertEqual(row, expected[idx], + self.assertEqual(row, expected[idx], "%d : %r != %r" % (idx, row, expected[idx])) rows.append(row) @@ -53,7 +53,7 @@ def test_reader(self): idx = -1 for row in reader: idx += 1 - self.assertEqual(row, expected[idx], + self.assertEqual(row, expected[idx], "%d : %r != %r" % (idx, row, expected[idx])) rows.append(row) diff --git a/examples/libtest/DictTest.py b/examples/libtest/DictTest.py index d07ba5bc9..4a1f93eb7 100644 --- a/examples/libtest/DictTest.py +++ b/examples/libtest/DictTest.py @@ -215,24 +215,24 @@ def testIteritems(self): a += x b += y self.assertEqual((a,b),(4,6)) - + class DICT(dict): pass - - + + d2 = DICT({1:2,3:4}) a,b = 0,0 for x,y in d2.iteritems(): a += x b += y self.assertEqual((a,b),(4,6)) - + d3 = dict() a,b = 0,0 for x,y in d3.iteritems(): a += x b += y self.assertEqual((a,b),(0,0)) - + def testUpdate(self): d1 = {1:2,3:4} d1.update({3:5,7:9}) diff --git a/examples/libtest/ExceptionTest.py b/examples/libtest/ExceptionTest.py index 7d76f9cc6..0da4fa3d8 100644 --- a/examples/libtest/ExceptionTest.py +++ b/examples/libtest/ExceptionTest.py @@ -23,7 +23,7 @@ def testTypeError(self): self.assertTrue(True, "the exception should have happened") return self.assertTrue(False, "the exception should have happened") - + def testExceptionOrdTrigger(self): try: x = ord(5) # shouldn't be a number @@ -69,7 +69,7 @@ def testCatchStringException(self): # str exceptions were removed since 2.6 if sys.version_info >= (2, 6): - return + return try: raise "test" diff --git a/examples/libtest/FunctionTest.py b/examples/libtest/FunctionTest.py index a35173e97..cf332c3f2 100644 --- a/examples/libtest/FunctionTest.py +++ b/examples/libtest/FunctionTest.py @@ -96,7 +96,7 @@ def testLambda(self): v = f(1,2,3,4) self.assertEqual(v[2][0], 3) self.assertEqual(v[2][1], 4) - + try: class ClassWithLambdas1: f1 = [lambda *args: args[0]] @@ -281,17 +281,17 @@ def fn3(x): return "b" self.assertEqual(fn3("b"), "abc") - + def shiftdecorator(si): def wrapper(fn): def decorated(*args, **kw): return fn(*args, **kw) + si return decorated return wrapper - + def fn4(v): return v - + @shiftdecorator(1) def fn4d1(v): return v @@ -299,7 +299,7 @@ def fn4d1(v): def fn4d2(v): return v fn4d3 = shiftdecorator(2)(fn4) - + self.assertEqual(fn4d1(1), 2) self.assertEqual(fn4d2(1), 3) self.assertEqual(fn4d3(1), 3) diff --git a/examples/libtest/GeneratorTest.py b/examples/libtest/GeneratorTest.py index 8c8bd29d9..1c7171efd 100644 --- a/examples/libtest/GeneratorTest.py +++ b/examples/libtest/GeneratorTest.py @@ -207,7 +207,7 @@ def fn(n): 'finally 3 (1)', 'finally 3 (2)', 'else 4 (1)', - 'else 4 (2)', + 'else 4 (2)', 'finally 4 (1)', 'finally 4 (2)']) @@ -563,7 +563,7 @@ def fn(value = None): self.assertEqual(r, [0, 1, None, 2, 2, 3, 4]) def testGenExp(self): - + g = (child for child in [1,2,3]) self.assertEqual(g.next(), 1) self.assertEqual(g.next(), 2) diff --git a/examples/libtest/LibTest.py b/examples/libtest/LibTest.py index 2f8887775..5383e1683 100644 --- a/examples/libtest/LibTest.py +++ b/examples/libtest/LibTest.py @@ -97,11 +97,11 @@ def main(): if IN_BROWSER: t.add(JSOTest) t.add(WindowTest) - + if sys.version_info >= (2, 7): from Syntax27Test import Syntax27Test t.add(Syntax27Test) - + from WithTest import WithTest t.add(WithTest) diff --git a/examples/libtest/ListTest.py b/examples/libtest/ListTest.py index 7e49977d1..3a237f139 100644 --- a/examples/libtest/ListTest.py +++ b/examples/libtest/ListTest.py @@ -1,5 +1,5 @@ from UnitTest import UnitTest, IN_JS -import sys +import sys class LetterNode(list): @@ -41,7 +41,7 @@ def testSliceGet(self): self.assertTrue(value[1] is 1) self.assertTrue(value[4] is 4) self.assertTrue(value[-3] is 2) - + l = [1, 2] self.assertEqual(l[True], 2) self.assertEqual(l[False], 1) @@ -92,7 +92,7 @@ def testSliceSet(self): self.assertTrue(value == [1, 11, 12, 3], "%s == [1, 11, 12, 3]" % value) value[3:] = [21,22,23] self.assertTrue(value == [1, 11, 12, 21, 22, 23], "%s == [1, 11, 12, 21, 22, 23]" % value) - + def testMultipleSliceSet(self): @@ -454,49 +454,49 @@ def testListContains(self): l = [{'monkey':1}, {'patch':1}, {'fish':1}, {'chips':1}] self.assertTrue({'fish':1} in l, "{'fish':1} in l") - - def testExtendedSlicing(self): - + + def testExtendedSlicing(self): + self.fail("Bug #xxx - need better __setitem__ implementation for builtin lists") return - + # slice object a = range(20) a[slice(2,10,3)] = [1,2,3] self.assertEqual(a, [0, 1, 1, 3, 4, 2, 6, 7, 3, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]) - + # deletion a = [0,1,2,3,4] del a[::2] self.assertEqual(a, [1,3]) - + a = range(5) del a[1::2] self.assertEqual(a, [0,2,4]) - + a = range(5) del a[1::-2] self.assertEqual(a, [0,2,3,4]) - + a = range(10) del a[::1000] self.assertEqual(a, [1, 2, 3, 4, 5, 6, 7, 8, 9]) - + # assignment a = range(10) a[::2] = [-1]*5 self.assertEqual(a, list([-1, 1, -1, 3, -1, 5, -1, 7, -1, 9])) - + a = list(range(10)) a[::-4] = [10]*3 self.assertEqual(a, list([0, 10, 2, 3, 4, 10, 6, 7, 8 ,10])) - + a = list(range(4)) a[::-1] = a self.assertEqual(a, list([3, 2, 1, 0])) - + a = list(range(10)) b = a[:] c = a[:] @@ -505,17 +505,17 @@ def testExtendedSlicing(self): c[2:3:] = list(["two", "elements"]) self.assertEqual(a, b) self.assertEqual(a, c) - + a = list(range(10)) a[::2] = tuple(range(5)) self.assertEqual(a, list([0, 1, 1, 3, 2, 5, 3, 7, 4, 9])) - + # causes segfault in older versions if sys.version_info < (2,5,5): return # test issue7788 a = list(range(10)) - del a[9::1<<333] + del a[9::1<<333] def testStr(self): self.assertEqual(str([0,1]), "[0, 1]") diff --git a/examples/libtest/NameTest.py b/examples/libtest/NameTest.py index 87e9060d4..66b7b3006 100644 --- a/examples/libtest/NameTest.py +++ b/examples/libtest/NameTest.py @@ -31,7 +31,7 @@ def testImportName(self): import foo as a self.assertEqual(a.__name__, 'foo') - # This test fails, but even the declaration of foo + # This test fails, but even the declaration of foo #(foo = object()) makes the test above fail too foo = object() import foo diff --git a/examples/libtest/NoInlineCodeTest.py b/examples/libtest/NoInlineCodeTest.py index 61bd44b03..c89ffe222 100644 --- a/examples/libtest/NoInlineCodeTest.py +++ b/examples/libtest/NoInlineCodeTest.py @@ -352,10 +352,10 @@ def fn(i, *args, **kwargs): collection.append((0, args, kwargs)) fn(1, *args, **kwargs) self.assertEqual( - collection, + collection, [ - (0, (2, 3), {'a': 'a', 'b': 'b'}), - (2, (), {}), + (0, (2, 3), {'a': 'a', 'b': 'b'}), + (2, (), {}), (1, (2, 3), {'a': 'a', 'b': 'b'}), ], ) diff --git a/examples/libtest/ReModuleTest.py b/examples/libtest/ReModuleTest.py index b660eae0e..ca2ecafd1 100644 --- a/examples/libtest/ReModuleTest.py +++ b/examples/libtest/ReModuleTest.py @@ -52,7 +52,7 @@ def testMatchBasics(self): m = re.match("1..4", "1234") self.assertFalse(m is None, """re.match("1..4", "1234")""") - + def testSearchBasics(self): self.searchTest('test 1', 'Ab.cd', 0, 'AbXcd', ['AbXcd'], (0,5)) self.searchTest('test 2', 'Ab.cd', 0, 'abXcd', None, (0,5)) diff --git a/examples/libtest/StringTest.py b/examples/libtest/StringTest.py index 6fbf208a8..55eaed998 100644 --- a/examples/libtest/StringTest.py +++ b/examples/libtest/StringTest.py @@ -163,7 +163,7 @@ def testStrTuple(self): def testStrList(self): self.assertEqual(str([5,6]), "[5, 6]") - + def testStrFloat(self): f1 = 1.5 self.assertEqual(str(f1), "1.5") diff --git a/examples/libtest/Syntax27Test.py b/examples/libtest/Syntax27Test.py index c9c3acfe2..b005b21b6 100644 --- a/examples/libtest/Syntax27Test.py +++ b/examples/libtest/Syntax27Test.py @@ -1,92 +1,92 @@ from UnitTest import UnitTest -import sys +import sys class Syntax27Test(UnitTest): def testSetLiteral(self): s = {1,2,3,1,2,3,1,2,3} self.assertEqual(s, set([1,2,3])) - + self.fail("Bug #XXX - None not supported in sets") return s = {1, 2, None, True, False, 2, 2, ('a',)} - self.assertEqual(s, set([False, True, 2, ('a',), None])) + self.assertEqual(s, set([False, True, 2, ('a',), None])) def testSetComprehensions(self): s = sum({i*i for i in range(100) if i&1 == 1}) self.assertEqual(s, 166650) self.fail("Bug #XXX - Set equality fails") - return - + return + s = {2*y + x + 1 for x in (0,) for y in (1,)} self.assertEqual(s, set([3])) - + l = list(sorted({(i,j) for i in range(3) for j in range(4)})) self.assertEqual(l, [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]) - + l = list(sorted({(i,j) for i in range(4) for j in range(i)})) self.assertEqual(l, [(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2)]) - + i = 20 s = sum({i*i for i in range(100)}) self.assertEqual(s, 328350) self.assertEqual(i, 20) - + def srange(n): return {i for i in range(n)} l = list(sorted(srange(10))) self.assertEqual(l, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) - + lrange = lambda n: {i for i in range(n)} l = list(sorted(lrange(10))) self.assertEqual(l, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) - + def grange(n): for x in {i for i in range(n)}: yield x l = list(sorted(grange(5))) self.assertEqual(l, [0, 1, 2, 3, 4]) - + s = {None for i in range(10)} self.assertEqual(s, set([None])) - + items = {(lambda i=i: i) for i in range(5)} s = {x() for x in items} self.assertEqual(s, set(range(5))) - + items = {(lambda: i) for i in range(5)} s = {x() for x in items} self.assertEqual(s, set([4])) - + items = {(lambda: y) for i in range(5)} y = 2 s = {x() for x in items} self.assertEqual(s, set([2])) - + def test_func(): items = {(lambda i=i: i) for i in range(5)} return {x() for x in items} self.assertEqual(test_func(), set(range(5))) - + def testDictComprehensions(self): k = "old value" d = { k: None for k in range(10) } self.assertEqual(d, {0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None}) self.assertEqual(k, 'old value') - + d = { k: k+10 for k in range(10) } self.assertEqual(d, {0: 10, 1: 11, 2: 12, 3: 13, 4: 14, 5: 15, 6: 16, 7: 17, 8: 18, 9: 19}) - + d = { k: v for k in range(10) for v in range(10) if k == v } self.assertEqual(d, {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}) - + d = { k: v for v in range(10) for k in range(v*9, v*10) } self.assertEqual(d, {9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4, 38: 4, 39: 4, 45: 5, 46: 5, 47: 5, 48: 5, 49: 5, 54: 6, 55: 6, 56: 6, 57: 6, 58: 6, 59: 6, 63: 7, 64: 7, 65: 7, 66: 7, 67: 7, 68: 7, 69: 7, 72: 8, 73: 8, 74: 8, 75: 8, 76: 8, 77: 8, 78: 8, 79: 8, 81: 9, 82: 9, 83: 9, 84: 9, 85: 9, 86: 9, 87: 9, 88: 9, 89: 9}) - + g = "outer" d = { k: g for k in range(3) } self.assertEqual(d, {0: 'outer', 1: 'outer', 2: 'outer'}) - + diff --git a/examples/libtest/VarsTest.py b/examples/libtest/VarsTest.py index d21dd2f78..1619d73fb 100644 --- a/examples/libtest/VarsTest.py +++ b/examples/libtest/VarsTest.py @@ -54,7 +54,7 @@ def testUnpack(self): x, y = l self.assertEqual(x, 1) self.assertEqual(y, 2) - + x = ((1, 2), 3, (4, 5)) (a, b), c, (d, e) = x self.assertEqual(a, 1) @@ -65,11 +65,11 @@ def testUnpack(self): self.assertEqual(d1, 4) self.assertEqual([a1, b1, c1, d1, d2, c2, b2, a2, a3], [1, 2, 3, 4, 5, 6, 7, 8, (9, 10)]) #a1, (b1, (c1, *c2), b2), a2, a3 = x # Py3 syntax - + class X(object): pass - - x = X() + + x = X() x.a = 1 d = {} l = [1,3,4] @@ -77,14 +77,14 @@ class X(object): self.assertEqual(l, [1, 10, 11, 4]) self.assertEqual(x.a, 20) self.assertEqual(d, {'zz': 30}) - + [a,b,c] = [1,2,3] self.assertEqual([a,b,c], [1,2,3]) [a,b,c] = 4,5,6 self.assertEqual([a,b,c], [4,5,6]) - + # XXX: Parser fails on this! - """ + """ a,b,c = {1,2,3} """ a,b,c = set([7,8,9]) @@ -124,14 +124,14 @@ def testGlobalsBltin(self): if 'sys' in globkeys2: globkeys2.remove('sys') # `global sys` in cpython does not make # it appear in globals() - self.assertEqual(set(globkeys2), + self.assertEqual(set(globkeys2), set(['changeme', 'foo', 'myfoo_value', 'data', 'UnitTest', 'import_sys', 'VarsTest', 'data_test', 'module_global_x', 'myget_foo_value', 'myfoo', ])) - + self.assertEqual(globs['__name__'], __name__) - + try: globals()['new_global_via_dict'] = 1 self.assertEqual(globals()['new_global_via_dict'], 1) @@ -145,10 +145,10 @@ def testDiscardNames(self): pass else: self.fail("Discarded names should trigger NameError if undefined, bug #584") - + class X(object): pass - + x = X() try: x.a @@ -156,46 +156,46 @@ class X(object): pass else: self.fail("Discarded getattr should trigger AttributeError if undefined, bug #584") - + def testAugmentedAssignments(self): a = a0 = 100 self.assertTrue(a is a0) a += 1 self.assertFalse(a is a0) self.assertEqual(a, 101) - + a -= 1 self.assertEqual(a, 100) - + a *= 2 self.assertEqual(a, 200) - + a /= 3 self.assertEqual(a, 66) - + a //= 60 self.assertEqual(a, 1) - + a = 15 a %= 10 self.assertEqual(a, 5) - + a **= 2 self.assertEqual(a, 25) - + a >>= 2 self.assertEqual(a, 6) - + a <<= 2 self.assertEqual(a, 24) - + a &= 16 self.assertEqual(a, 16) - + a ^= 8 self.assertEqual(a, 24) - + a |= 32 self.assertEqual(a, 56) - - + + diff --git a/examples/libtest/WithTest.py b/examples/libtest/WithTest.py index 1d1f89c7e..c5e141587 100644 --- a/examples/libtest/WithTest.py +++ b/examples/libtest/WithTest.py @@ -19,25 +19,25 @@ def __exit__(self, *exc_info): self.exc_info = exc_info if self.gobble: return True - + def testSimple(self): with self.Dummy(): pass - + with self.Dummy() as v: pass - + d = self.Dummy() with d: pass self.assertTrue(d.enter_called) self.assertTrue(d.exit_called) - + z = None with self.Dummy(10) as v: z = v self.assertEqual(z, 10) - + self.fail("Bug #XXX - With statement fails for unknown reason") return @@ -45,13 +45,13 @@ def testSimple(self): with d: raise Exception() self.assertEqual(type(d.exc_info[1]), Exception) - + def testNested(self): l = None with self.Dummy(1) as v1, self.Dummy(2) as v2, self.Dummy(3) as v3: l = [v1, v2, v3] self.assertEqual(l, [1,2,3]) - + l = None with self.Dummy(1) as v1: l = [] @@ -61,30 +61,30 @@ def testNested(self): with self.Dummy(3) as v3: l.append(v3) self.assertEqual(l, [1,2,3]) - + def testComplexAssign(self): d = {1: [0, 1, 2]} with self.Dummy('z') as d[1]: self.assertEqual(d, {1:'z'}) - + d = {1: [0, 1, 2]} with self.Dummy('z') as d[1][0]: self.assertEqual(d[1][0], 'z') self.assertEqual(d, {1: ['z', 1, 2]}) - + d = {1: [0, 1, 2]} with self.Dummy('z') as d.values()[0][1]: self.assertEqual(d, {1: [0, 'z', 2]}) - + d = {1: [0, 1, 2]} with self.Dummy(['a', 'b', 'c']) as (d[1][0], d[1][1], d[1][2]): self.assertEqual(d, {1: ['a', 'b', 'c']}) - + d = {1: [0, 1, 2]} with self.Dummy(['a', 'b', 'c']) as (d[1], d[2], d[3]): self.assertEqual(d, {1:'a', 2:'b', 3:'c'}) - - + + def testFlowControl(self): # Hard to make work correctly! # Should walk ast and track them @@ -94,9 +94,9 @@ def return_stmt(): with self.Dummy(): if i == 2: return i - + self.assertEqual(return_stmt(), 2) - + def break_stmt(): x = 0 for i in range(10): @@ -105,7 +105,7 @@ def break_stmt(): if i == 2: break return x - + self.assertEqual(break_stmt(), 2) def continue_stmt(): @@ -116,7 +116,6 @@ def continue_stmt(): continue x += 100 return x - + self.assertEqual(continue_stmt(), 10) """ - \ No newline at end of file diff --git a/examples/libtest/builtin.py b/examples/libtest/builtin.py index bf1530c31..7358ac1fa 100644 --- a/examples/libtest/builtin.py +++ b/examples/libtest/builtin.py @@ -1,6 +1,6 @@ # This module is used in builtin test # It should only be used there! It is to check for conditional -# imports, which will succeed anyway, if the imported module is +# imports, which will succeed anyway, if the imported module is # imported somewhere else value = 1 diff --git a/examples/lightout/lightout.py b/examples/lightout/lightout.py index d636b1b1c..a3a558d74 100644 --- a/examples/lightout/lightout.py +++ b/examples/lightout/lightout.py @@ -28,20 +28,20 @@ def __init__(self,i,j): FocusWidget.__init__(self, element) self.redraw() self.addClickListener(self) - + def redraw(self): if self.light: self.setStyleName("on") else: self.setStyleName("off") - + def toggle(self): if self.light: self.light = False else: self.light = True self.redraw() - + def onClick(self,sender): if self.i>0: self.parent.getWidget(self.i-1,self.j).toggle() @@ -53,12 +53,12 @@ def onClick(self,sender): self.parent.getWidget(self.i,self.j+1).toggle() self.toggle() self.check_win() - + def check_win(self): for i in range(self.parent.getRowCount()): for j in range(self.parent.getColumnCount()): if self.parent.getWidget(i,j).light: - return + return Window.alert('You win!!! But can you beat the next level?') global game game.next_level() @@ -68,7 +68,7 @@ def __init__(self,level): self.level = level SimplePanel.__init__(self) self.start_game(self.level) - + def start_game(self, level=None): if level is not None: self.level = level @@ -80,7 +80,7 @@ def start_game(self, level=None): gc = GridCell(i,j) grid.setWidget(i,j,gc) self.add(grid) - + def next_level(self): self.remove(self.getWidget()) self.level+=1 diff --git a/examples/mail/AboutDialog.py b/examples/mail/AboutDialog.py index 123a55fcf..0c192807c 100644 --- a/examples/mail/AboutDialog.py +++ b/examples/mail/AboutDialog.py @@ -9,7 +9,7 @@ from pyjamas.ui import HasAlignment class AboutDialog(DialogBox): - + LOGO_IMAGE = "http://trac.pyworks.org/pyjamas/chrome/site/pyjamas-logo-small.png" def __init__(self): @@ -22,7 +22,7 @@ def __init__(self): # Create a DockPanel to contain the 'about' label and the 'OK' button. outer = DockPanel() outer.setSpacing(4) - + outer.add(Image(AboutDialog.LOGO_IMAGE), DockPanel.WEST) # Create the 'OK' button, along with a listener that hides the dialog @@ -52,7 +52,7 @@ def __init__(self): def onClick(self, sender): self.hide() - + def onKeyDownPreview(self, key, modifiers): # Use the popup's key preview hooks to close the dialog when either # enter or escape is pressed. diff --git a/examples/mail/Contacts.py b/examples/mail/Contacts.py index 4a1cc9626..bc59db061 100644 --- a/examples/mail/Contacts.py +++ b/examples/mail/Contacts.py @@ -26,12 +26,12 @@ def __init__(self, contact): emailLabel = Label(contact.email) inner.add(nameLabel) inner.add(emailLabel) - + panel = HorizontalPanel() panel.setSpacing(4) panel.add(Image(contact.photo)) panel.add(inner) - + self.add(panel) self.setStyleName("mail-ContactPopup") nameLabel.setStyleName("mail-ContactPopupName") @@ -66,7 +66,7 @@ def __init__(self): def addContact(self, contact): link = HTML("" + contact.name + "") self.panel.add(link) - + # Add a click listener that displays a ContactPopup when it is clicked. listener = ContactListener(contact, link) link.addClickListener(listener) @@ -75,7 +75,7 @@ class ContactListener: def __init__(self, contact, link): self.cont = contact self.link = link - + def onClick(self, sender): if (sender == self.link): popup = ContactPopup(self.cont) diff --git a/examples/mail/Logger.py b/examples/mail/Logger.py index 062241c15..e4729204a 100644 --- a/examples/mail/Logger.py +++ b/examples/mail/Logger.py @@ -14,7 +14,7 @@ def __init__(self): self.resize(len(self.targets)+1, 2) self.setBorderWidth("1px") self.counter=0 - + self.setHTML(0, 0, "Log") self.setText(1, 0, "app") for i in range(len(self.targets)): @@ -26,30 +26,30 @@ def addTarget(self, target): self.resize(len(self.targets)+1, 2) self.setText(len(self.targets), 0, target) return self.targets.index(target) - + def write(self, target, message): self.counter+=1 - + if target=='': target='app' try: target_idx=self.targets.index(target) except ValueError: target_idx = -1 - + # add new target if target_idx<0: target_idx=self.addTarget(target) - - target_row=target_idx+1 + + target_row=target_idx+1 old_text=self.getHTML(target_row, 1) log_line="%d: " % self.counter + message if old_text==' ': - new_text=log_line + new_text=log_line else: new_text=old_text + "
" + log_line - self.setHTML(target_row, 1, new_text) + self.setHTML(target_row, 1, new_text) def Logger(target="", message=""): global _logger @@ -58,5 +58,5 @@ def Logger(target="", message=""): _logger = LoggerCls() _logger.write(target, message) - + return _logger diff --git a/examples/mail/Mail.py b/examples/mail/Mail.py index 1825dfead..7d3e91147 100644 --- a/examples/mail/Mail.py +++ b/examples/mail/Mail.py @@ -30,7 +30,7 @@ def onModuleLoad(self): # 'singleton'. mailList = MailList(self.singleton) mailList.setWidth("100%") - + # Create the right panel, containing the email list & details. rightPanel.add(mailList) rightPanel.add(self.mailDetail) @@ -56,13 +56,13 @@ def onModuleLoad(self): # because we want to take advantage of the entire client area. Window.enableScrolling(False) Window.setMargin("0px") - + # Finally, add the outer panel to the RootPanel, so that it will be # displayed. #RootPanel.get().add(outer) # FIXME get# RootPanel().add(outer) RootPanel().add(Logger()) - + # Call the window resized handler to get the initial sizes setup. Doing # this in a deferred command causes it to occur after all widgets' sizes # have been computed by the browser. diff --git a/examples/mail/MailDetail.py b/examples/mail/MailDetail.py index 2e18bef5a..e615e3295 100644 --- a/examples/mail/MailDetail.py +++ b/examples/mail/MailDetail.py @@ -50,7 +50,7 @@ def setItem(self, item): self.sender.setHTML("From: " + item.sender) self.recipient.setHTML("To: foo@example.com") self.body.setHTML(item.body) - + def adjustSize(self, windowWidth, windowHeight): scrollWidth = windowWidth - self.scroller.getAbsoluteLeft() - 9 if (scrollWidth < 1): diff --git a/examples/mail/MailItems.py b/examples/mail/MailItems.py index 2a313cd49..449b9a9a8 100644 --- a/examples/mail/MailItems.py +++ b/examples/mail/MailItems.py @@ -44,7 +44,7 @@ def __init__(self): def getMailItemCount(self): return len(self.items) - + def getMailItem(self, index): if (index >= len(self.items)): return None @@ -74,5 +74,5 @@ def createFakeMail(self): if (self.fragmentIdx == len(MailItems.fragments)): self.fragmentIdx = 0 i = i + 1 - + return MailItem(sender, email, subject, body) diff --git a/examples/mail/MailList.py b/examples/mail/MailList.py index 137354dfe..660fef0d3 100644 --- a/examples/mail/MailList.py +++ b/examples/mail/MailList.py @@ -70,7 +70,7 @@ def onClick(self, sender): self.styleRow(self.selectedRow, False) self.selectedRow = -1 self.update() - + elif (sender == self.newerButton): # Move back a page. self.startIndex = self.startIndex - MailList.VISIBLE_EMAIL_COUNT @@ -108,7 +108,7 @@ def selectRow(self, row): item = MailItems().getMailItem(self.startIndex + row) if item is None: return - + self.styleRow(self.selectedRow, False) self.styleRow(row, True) diff --git a/examples/mail/Mailboxes.py b/examples/mail/Mailboxes.py index 40699ee5e..de34b8a32 100644 --- a/examples/mail/Mailboxes.py +++ b/examples/mail/Mailboxes.py @@ -2,14 +2,14 @@ from pyjamas.ui.Tree import Tree from pyjamas.ui.TreeItem import TreeItem - + class Mailboxes(Composite): def __init__(self): Composite.__init__(self) self.tree = Tree() root = TreeItem(self.imageItemHTML("home.gif", "foo@example.com")) - self.tree.addItem(root) + self.tree.addItem(root) inboxItem = self.addImageItem(root, "Inbox") self.addImageItem(root, "Drafts") self.addImageItem(root, "Templates") diff --git a/examples/maparea/MapAreaDemo.py b/examples/maparea/MapAreaDemo.py index 58ec6e737..c9ee1290b 100644 --- a/examples/maparea/MapAreaDemo.py +++ b/examples/maparea/MapAreaDemo.py @@ -25,7 +25,7 @@ def onModuleLoad(self): height = 215 #px scale = 1.5 img = Image( - "babykatie_small.jpg", + "babykatie_small.jpg", Width="%dpx" % int(scale * width), Height="%dpx" % int(scale * height), ) @@ -51,24 +51,24 @@ def onModuleLoad(self): ) areas = [ \ NamedMapArea( - "right eye", - "circle", + "right eye", + "circle", [scale * i for i in [73, 97, 7]], ), NamedMapArea( - "left eye", - "circle", + "left eye", + "circle", [scale * i for i in [116, 88, 5]], ), NamedMapArea( - "nose", - "rect", + "nose", + "rect", [scale * i for i in [88, 97, 115, 115]], Href="http://lkcl.net", ), NamedMapArea( - "mouth", - "polygon", + "mouth", + "polygon", [scale * i for i in [82, 129, 102, 124, 119, 119, 121, 125, 103, 132, 79, 133]], ), ] @@ -82,19 +82,19 @@ def onModuleLoad(self): hpanel.add(map) hpanel.add(imagepanel) hpanel.add(msgpanel) - + RootPanel().add(hpanel) class NamedMapArea(MapArea): """ An area inside an imagemap with a name """ - + def __init__(self, areaname, shape, coords, Href="", **kwargs): self.areaname = areaname coords = ", ".join(["%d" % int(i) for i in coords]) MapArea.__init__(self, shape, coords, Href=Href, **kwargs) - + class MapClickHandler: @@ -110,7 +110,7 @@ def _mouseActionMessage(self, name, action, x=None, y=None): def onMouseMove(self, sender, x, y): self._mouseActionMessage(sender.areaname, "move", x, y) - + def onMouseDown(self, sender, x, y): self._mouseActionMessage(sender.areaname, "down", x, y) @@ -127,7 +127,7 @@ def onClick(self, sender): msg = "you clicked on baby katie's " + sender.areaname self.msgarea2.setText(msg) log.debug(msg) - + if __name__ == '__main__': pyjd.setup("http://127.0.0.1/examples/maparea/public/MapAreaDemo.html") diff --git a/examples/media/Media.py b/examples/media/Media.py index e3f9ce037..a8e484f4e 100644 --- a/examples/media/Media.py +++ b/examples/media/Media.py @@ -13,13 +13,13 @@ Controls=True, src="http://acfauk/public/services/files.py?video=sample&ext=wmv", #src="http://172.20.0.1/home/Downloads/Jungle_alcohol.wmv") - #src="http://172.20.0.1/home/kiss.the.girl.mp4") + #src="http://172.20.0.1/home/kiss.the.girl.mp4") #src="file:/home/lkcl/kiss.the.girl.mp4") #src="file:/home/lkcl/gizmo.webm", Poster="http://acfauk/public/img/coffee_cup_01.png", ) RootPanel().add(v) - + if False: a = Audio(Width="160px", Height="32px", StyleName="teststyle", @@ -30,6 +30,6 @@ #src="file:/home/lkcl/Lry_Crane_Copy.mp3") #src="file:/home/lkcl/test.ogg") RootPanel().add(a) - + pyjd.run() diff --git a/examples/minesweeper/minesweeper.py b/examples/minesweeper/minesweeper.py index 6ac736cfa..5d6552ff6 100644 --- a/examples/minesweeper/minesweeper.py +++ b/examples/minesweeper/minesweeper.py @@ -41,10 +41,10 @@ class MineMenuBar(MenuBar): def __init__(self, game): self.game = game super(MineMenuBar, self).__init__() - + body = doc().getElementsByTagName('body').item(0) body.setAttribute('id', 'Beginner') - + menu_game = MenuBar(True) menu_game.addItem('New', MenuCmd(self, 'New')) menu_game.addItem(self.span_text('Beginner'), True, \ @@ -55,14 +55,14 @@ def __init__(self, game): MenuCmd(self, 'Expert')) menu_game.addItem(self.span_text('Custom'), True, \ MenuCmd(self, 'Custom')) - + menu_help = MenuBar(True) #menu_help.addItem('Instructions', MenuCmd(self, 'Instructions')) menu_help.addItem('About', MenuCmd(self, 'About')) - + self.addItem(MenuItem('Game', menu_game)) self.addItem(MenuItem('Help', menu_help)) - + def span_text(self, text): return '%s' % (text, text) @@ -70,12 +70,12 @@ class MenuCmd: def __init__(self, menu, command): self.menu = menu self.command = command - + def execute(self): if self.command in ('Beginner', 'Intermediate', 'Expert', 'Custom'): body = doc().getElementsByTagName('body').item(0) body.setAttribute('id', self.command) - + modes = {'New': [(0, 0), 0], 'Beginner': [(8, 8), 1], 'Intermediate': [(16, 16), 2], @@ -92,44 +92,44 @@ def execute(self): pass elif self.command == 'About': self.show_about() - + def show_custom(self): self.dialog = DialogBox(StyleName='custom-dialog') self.dialog.setHTML('Custom Settings') - + contents = VerticalPanel(StyleName='contents') self.dialog.setWidget(contents) - + # contents of contents rows = HorizontalPanel() columns = HorizontalPanel() bombs = HorizontalPanel() buttons = HorizontalPanel() - + for each in (rows, columns, bombs, buttons): contents.add(each) - + rows.add(Label('Rows:')) self.row = TextBox() rows.add(self.row) - + columns.add(Label('Columns:')) self.column = TextBox() columns.add(self.column) - + bombs.add(Label('Bombs:')) self.bomb = TextBox() bombs.add(self.bomb) - + buttons.add(Button("OK", getattr(self, 'new_game'))) buttons.add(Button("Cancel", getattr(self, 'close_dialog'))) - + left = (Window.getClientWidth() - 201) / 2 top = (Window.getClientHeight() - 190) / 2 self.dialog.setPopupPosition(left, top) - + self.dialog.show() - + def new_game(self, event): try: row = int(self.row.getText()) @@ -151,23 +151,23 @@ def new_game(self, event): else: self.menu.game.next_game((row, column), bomb) self.close_dialog() - + def close_dialog(self, event): self.dialog.hide() - + def show_about(self): self.dialog = PopupPanel(StyleName='about', autoHide=True) - + contents = HTMLPanel('', StyleName='contents') self.dialog.setWidget(contents) - + html = '

MineSweeper written in Python with ' \ 'Pyjamas

' \ '

Send comments to ' \ '' \ 'suzan.shakya@gmail.com.

' contents.setHTML(html) - + left = (Window.getClientWidth() - 294) / 2 top = (Window.getClientHeight() - 112) / 2 self.dialog.setPopupPosition(left, top) @@ -177,37 +177,37 @@ class Smiley(FocusPanel): def __init__(self, game): self.game = game super(Smiley, self).__init__(StyleName='facesmile') - + self.sinkEvents(Event.ONCONTEXTMENU) self.addClickListener(self) self.addMouseListener(self) self.pressed = False - + def onClick(self, sender): self.game.restart() - + def onMouseDown(self, sender, x, y): self.pressed = True self.previousStyleName = self.getStyleName() self.setStyleName('faceooh') - + def onMouseUp(self, sender, x, y): if self.pressed: self.pressed = False self.setStyleName(self.previousStyleName) - + def onMouseLeave(self, sender): self.onMouseUp(sender, 0, 0) class RemoteHandler: def __init__(self, game): self.game = game - + def onRemoteResponse(self, response, request_info): if request_info.method == 'get_scores': self.game.toppers = response self.load_top_scores() - + def load_top_scores(self): html = "

These are the top MineSweepers.

" html += "" @@ -224,7 +224,7 @@ def load_top_scores(self): html += "
" html += "" SCORES.setHTML(html) - + def onRemoteError(self, code, message, request_info): LOG.setHTML(str(message)) Timer(5000, lambda: LOG.setHTML('')) @@ -233,23 +233,23 @@ class RemainingMineHandler: """handler for counter, only active when counter is 000""" def __init__(self, game): self.game = game - + def onClick(self, sender): self.game.counter.setStyleName('digit counter') - + bomb_explodes_on = [one for one in self.game.bombed_cells \ if one.state != 1] if bomb_explodes_on: self.game.show_all_bombs(bomb_explodes_on) # the above method will set game.started == False, so set it True self.game.started = True - + for one in self.game.get_all_cells(): if not self.game.started: break elif one.state in (0, 2) and one.count != -1: self.game.grid.onClick(one) - + self.game.started = False if bomb_explodes_on: self.game.face.setStyleName('facedead') @@ -260,10 +260,10 @@ def __init__(self, x, y, grid): self.x = x self.y = y self.grid = grid - + self.count = 0 # count of surr bombs. -1 if it contains bomb self.state = 0 # 0 = blank, 1 = flagged, 2 = qmarked, 3 = opened - + # mock self.element as if it were td associated with this cell. # because we won't be creating div inside td. self.element = grid.cellFormatter.getElement(x, y) @@ -275,16 +275,16 @@ def __init__(self, game, row, column): self.sinkEvents(Event.ONCONTEXTMENU) self.sinkEvents(Event.ONMOUSEDOWN | Event.ONMOUSEUP | Event.ONMOUSEOUT) self.game = game - + self.cells = [] for i in xrange(row): self.cells.append([]) for j in xrange(column): self.cells[-1].append(Cell(i, j, self)) - + def getCell(self, row, column): return self.cells[row][column] - + def onBrowserEvent(self, event): DOM.eventPreventDefault(event) if not self.game.started: @@ -297,7 +297,7 @@ def onBrowserEvent(self, event): row = DOM.getChildIndex(table, tr) column = DOM.getChildIndex(tr, td) target_cell = self.getCell(row, column) - + type = DOM.eventGetType(event) event_mapper = {'click': 'onClick', 'contextmenu': 'onRightClick', @@ -307,7 +307,7 @@ def onBrowserEvent(self, event): event_handler = event_mapper.get(type) if event_handler: getattr(self, event_handler)(target_cell) - + def onClick(self, target): if target.state == 1: return @@ -317,13 +317,13 @@ def onClick(self, target): target.setStyleName('opened') target.state = 3 self.game.count_opened_cells += 1 - + if self.game.first_click: self.game.first_click = False self.game.onTimer(target) if target.count == -1: self.game.move_to_extra_mine(target) - + if target.count == -1: self.game.show_all_bombs([target]) return @@ -331,9 +331,9 @@ def onClick(self, target): self.game.open_neighboring_cells(target) else: setColorfulHTML(target.getElement(), target.count) - + self.game.check_win() - + def onRightClick(self, target): if target.state == 3: return @@ -351,10 +351,10 @@ def onRightClick(self, target): elif target.state == 2: target.setStyleName('blank') target.state = 0 - + self.game.set_counter() self.game.check_win() - + def onMouseDown(self, target): if target.state == 0: target.addStyleName('pressed') @@ -363,13 +363,13 @@ def onMouseDown(self, target): self.game.press_neighbor_cells(target) self.game.face.setStyleName('faceooh') self.game.no_of_click += 1 - + def onMouseUp(self, target): for one in self.game.to_be_released: one.removeStyleName('pressed') self.game.to_be_released = [] self.game.face.setStyleName('facesmile') - + def onMouseLeave(self, target): self.onMouseUp(target) @@ -377,7 +377,7 @@ class Game(VerticalPanel): def __init__(self, row, column=0): super(Game, self).__init__(StyleName='game') self.sinkEvents(Event.ONCONTEXTMENU) # to disable right click - + self.row = row self.column = column or row self.level = 1 @@ -385,64 +385,64 @@ def __init__(self, row, column=0): self.remote = DataService() self.remote_handler = RemoteHandler(self) self.remote.get_scores(self.remote_handler) - + # contents of Game menubar = MineMenuBar(self) score_board = HorizontalPanel(StyleName='score-board') self.grid_panel = SimplePanel(StyleName='grid-panel') - + self.add(menubar) self.add(score_board) self.add(self.grid_panel) - + # contents of score_board self.counter = Label('000', StyleName='digit counter') self.face = Smiley(self) self.timer = Label('000', StyleName='digit timer') - + for one in (self.counter, self.face, self.timer): score_board.add(one) score_board.setCellWidth(self.face, '100%') - + self.create_grid() self.start() - + def onBrowserEvent(self, event): # prevent right click context menu as well as all the other events. DOM.eventPreventDefault(event) - + def create_grid(self): # contents of self.grid_panel self.grid = CustomGrid(self, self.row, self.column) self.grid_panel.add(self.grid) - + def start(self, no_of_bomb=0): self.time = -1 self.started = True self.first_click = True - + self.bombed_cells = [] self.flagged_cells = [] self.to_be_released = [] # cells to be released after being pressed self.count_opened_cells = 0 self.no_of_click = 0 - + self.squares = self.row * self.column self.no_of_bomb = no_of_bomb or int((self.squares * 10) / 64) self.no_of_safe_zones = self.squares - self.no_of_bomb - + self.set_counter() self.timer.setText('000') - + self.generate_bombs() self.face.setStyleName('facesmile') - + def get_all_cells(self): for i in xrange(self.row): for j in xrange(self.column): one = self.grid.getCell(i, j) yield one - + def get_neighbors(self, cell): x = cell.x y = cell.y @@ -454,17 +454,17 @@ def get_neighbors(self, cell): if (i,j) != (x, y): one = self.grid.getCell(i, j) yield one - + def set_counter(self): next_value = self.no_of_bomb - len(self.flagged_cells) - + if next_value == 0 and self.started: self.counter.setStyleName('digit counter-blue') self.counter.addClickListener(RemainingMineHandler(self)) else: self.counter.setStyleName('digit counter') self.counter._clickListeners = [] - + if next_value < 0: template = '-00' next_value = abs(next_value) @@ -473,7 +473,7 @@ def set_counter(self): value = str(next_value) value = template[:-len(value)] + value self.counter.setText(value) - + def onTimer(self, target): if not self.started or self.first_click: return @@ -486,7 +486,7 @@ def onTimer(self, target): else: self.started = False self.face.setStyleName('faceclock') - + def sample(self, population, k): # pyjamas doesn't support random.sample but random.choice seq = list(population) @@ -496,7 +496,7 @@ def sample(self, population, k): seq.remove(pick) s.append(pick) return s - + def generate_bombs(self): # generate 1 extra mine so that if user's first click is bomb, move that bombs = self.sample(xrange(self.squares), self.no_of_bomb+1) @@ -514,7 +514,7 @@ def generate_bombs(self): for one in self.get_neighbors(mine): if one.count != -1: one.count += 1 - + def move_to_extra_mine(self, to_be_moved): to_be_moved.count = 0 self.bombed_cells.remove(to_be_moved) @@ -523,13 +523,13 @@ def move_to_extra_mine(self, to_be_moved): to_be_moved.count += 1 else: one.count -= 1 - + self.extra_mine.count = -1 self.bombed_cells.append(self.extra_mine) for one in self.get_neighbors(self.extra_mine): if one.count != -1: one.count += 1 - + def press_neighbor_cells(self, cell): self.count_flags = 0 self.bomb_explodes_on = [] @@ -544,14 +544,14 @@ def press_neighbor_cells(self, cell): else: if one.count == -1: self.bomb_explodes_on.append(one) - + def open_if_satisfies(self, cell): if self.count_flags == cell.count: if self.bomb_explodes_on: self.show_all_bombs(self.bomb_explodes_on) else: self.open_neighboring_cells(cell) - + def open_neighboring_cells(self, cell): if not self.started: return @@ -565,7 +565,7 @@ def open_neighboring_cells(self, cell): else: setColorfulHTML(one.getElement(), one.count) self.check_win() - + def check_win(self): if not self.started: return @@ -585,7 +585,7 @@ def check_win(self): self.remote.add_score(name, self.level, self.time, \ self.no_of_click, self.remote_handler) self.add_player_to_toppers(name) - + def add_player_to_toppers(self, name): current_level = self.level - 1 toppers_in_this_level = self.toppers[current_level] @@ -593,21 +593,21 @@ def add_player_to_toppers(self, name): self.toppers[current_level] = sorted(toppers_in_this_level, \ key=lambda score: score[1]) self.remote_handler.load_top_scores() - + def show_all_bombs(self, bomb_explodes_on=[]): self.started = False self.face.setStyleName('facedead') - + for one in self.bombed_cells: if one.state != 1: one.setStyleName('cell bombrevealed') for one in self.flagged_cells: if one.count != -1: one.setStyleName('cell bombmisflagged') - + for one in bomb_explodes_on: one.setStyleName('cell bombdeath') - + def next_game(self, level=None, no_of_bomb=0): current_level = (self.row, self.column) if not level or level == (0,0) or level == current_level: @@ -621,7 +621,7 @@ def next_game(self, level=None, no_of_bomb=0): self.grid_panel.remove(self.grid) self.create_grid() self.start(no_of_bomb) - + def restart(self, no_of_bomb=0): for one in self.get_all_cells(): one.count = 0 @@ -635,7 +635,7 @@ def restart(self, no_of_bomb=0): LOG = HTMLPanel('', StyleName='log') SCORES = HTMLPanel('', StyleName='scores') game = Game(8, 8) - + RootPanel('content').add(game) RootPanel('content').add(SCORES) RootPanel('content').add(LOG) diff --git a/examples/misc/djangotasks/todo/views.py b/examples/misc/djangotasks/todo/views.py index 64570072d..6833c56e8 100644 --- a/examples/misc/djangotasks/todo/views.py +++ b/examples/misc/djangotasks/todo/views.py @@ -1,7 +1,7 @@ # Create your views here. from django.pimentech.network import * -from todo.models import Todo +from todo.models import Todo service = JSONRPCService() diff --git a/examples/misc/djangowanted/media/Popups.py b/examples/misc/djangowanted/media/Popups.py index 29efc737c..4ab4c1687 100644 --- a/examples/misc/djangowanted/media/Popups.py +++ b/examples/misc/djangowanted/media/Popups.py @@ -10,18 +10,18 @@ class FileDialog(DialogBox): def __init__(self, url): DialogBox.__init__(self) self.setText("Upload Files") - + iframe = Frame(url) closeButton = Button("Close", self) msg = HTML("

Upload files, here. Please avoid spaces in file names.
(rename the file before uploading)
", True) dock = DockPanel() dock.setSpacing(4) - + dock.add(closeButton, DockPanel.SOUTH) dock.add(msg, DockPanel.NORTH) dock.add(iframe, DockPanel.CENTER) - + dock.setCellHorizontalAlignment(closeButton, HasAlignment.ALIGN_RIGHT) dock.setCellWidth(iframe, "100%") dock.setWidth("100%") diff --git a/examples/misc/djangowanted/media/WebPage.py b/examples/misc/djangowanted/media/WebPage.py index e4a5096d6..2d59c7ca5 100644 --- a/examples/misc/djangowanted/media/WebPage.py +++ b/examples/misc/djangowanted/media/WebPage.py @@ -57,13 +57,13 @@ def onClick(self, sender): self.form.update(v) else: self.form.save(v) - + def onErrors(self, form, response): log.debug("onErrors %s" % repr(response)) - + def onSaveDone(self, form, response): log.debug("onSave %s" % repr(response)) - + def onModuleLoad(self): self.pages = DataService() @@ -100,7 +100,7 @@ def onHistoryChanged(self, token): self.pages.getPageByName(token, self) def setPage(self, ref): - + htp = self.pages[ref] if htp == self.current_page: return @@ -137,7 +137,7 @@ def __init__(self): class WantedService(JSONProxy): def __init__(self): JSONProxy.__init__(self, "/services/wanted/", - ["getItem", + ["getItem", "getItems"]) class DataService(JSONProxy): diff --git a/examples/misc/djangowanted/media/WebPageEdit.py b/examples/misc/djangowanted/media/WebPageEdit.py index 26fce7f56..938732160 100644 --- a/examples/misc/djangowanted/media/WebPageEdit.py +++ b/examples/misc/djangowanted/media/WebPageEdit.py @@ -15,8 +15,8 @@ fileedit_url = '/fckeditor/editor/filemanager/browser/default/browser.html?Connector=/fckeditor%2Feditor%2Ffilemanager%2Fconnectors%2Fpy%2Fconnector.py' # good grieeef, could this get any longer?? -from HTMLDialog import HTMLDialog -from Popups import FileDialog +from HTMLDialog import HTMLDialog +from Popups import FileDialog class WebPageEdit(Composite): def __init__(self, sink): @@ -42,7 +42,7 @@ def __init__(self, sink): self.todoList.addClickListener(self) self.fDialogButton = Button("Upload Files", self) - + self.status = HTML() panel.add(HTML("Status:")) @@ -134,8 +134,8 @@ def onRemoteResponse(self, response, request_info): self.todoTextName.setText(item['fields']['name']) self.todoTextArea.setHTML(item['fields']['text']) - elif (request_info.method == 'getPages' or - request_info.method == 'addPage' or + elif (request_info.method == 'getPages' or + request_info.method == 'addPage' or request_info.method == 'deletePage'): self.status.setHTML(self.status.getText() + "HERE!") self.todoList.clear() diff --git a/examples/misc/djangowanted/testjsonrpc.py b/examples/misc/djangowanted/testjsonrpc.py index f30540c1a..2717e97de 100644 --- a/examples/misc/djangowanted/testjsonrpc.py +++ b/examples/misc/djangowanted/testjsonrpc.py @@ -52,9 +52,9 @@ def notest_createanddeleteitem(self): print reply item = reply["result"] self.assert_(item is None) - + def test_itemform(self): - reply = self.f.itemform({}, {"describe": + reply = self.f.itemform({}, {"describe": ['id', 'name', 'description', 'short_description', 'price', 'numdoors', @@ -62,7 +62,7 @@ def test_itemform(self): pprint(reply) d = {'name': 'fred', 'short_description': 'joe', 'description': 'longer', 'price': 20, 'vehicletype': 'a car', 'numdoors': '5'} - reply = self.f.itemform(d, {"save": + reply = self.f.itemform(d, {"save": ['name', 'description', 'short_description', 'price', 'numdoors', @@ -83,7 +83,7 @@ def test_itemform(self): def notest_itemformerror(self): d = {'name': 'fred', 'short_description': 'joe', 'description': 'longer', 'price': 20, 'vehicletype': 'a car', 'numdoors': 'x' * 101} - reply = self.f.itemform(d, {"save": + reply = self.f.itemform(d, {"save": ['name', 'description', 'short_description', 'price', 'numdoors', diff --git a/examples/misc/djangowanted/wanted/forms.py b/examples/misc/djangowanted/wanted/forms.py index af7976265..afb182ba0 100644 --- a/examples/misc/djangowanted/wanted/forms.py +++ b/examples/misc/djangowanted/wanted/forms.py @@ -1,5 +1,5 @@ from django.forms import ModelForm -from django import forms +from django import forms from wanted.models import * class FlagForm(ModelForm): diff --git a/examples/misc/djangowanted/wanted/jsonrpc.py b/examples/misc/djangowanted/wanted/jsonrpc.py index 86e0166df..4b1e389cc 100644 --- a/examples/misc/djangowanted/wanted/jsonrpc.py +++ b/examples/misc/djangowanted/wanted/jsonrpc.py @@ -32,10 +32,10 @@ def error(id, code, message): class JSONRPCService: def __init__(self, method_map=None): self.method_map = method_map or {} - + def add_method(self, name, method): self.method_map[name] = method - + def __call__(self, request, extra=None): # We do not yet support GET requests, something pyjamas does # not use anyways. @@ -65,7 +65,7 @@ def __call__(self, request, extra=None): def jsonremote(service): """Make JSONRPCService a decorator so that you can write : - + from jsonrpc import JSONRPCService chatservice = JSONRPCService() @@ -103,7 +103,7 @@ def remotify(func): # (r'^formsservice/$', 'djangoapp.views.processor'), -from django import forms +from django import forms def builderrors(form): d = {} @@ -206,20 +206,20 @@ def __process(self, request, params, command=None): return describe_fields(f.fields, field_names) elif command.has_key('delete'): - instance = f.delete(**data) + instance = f.delete(**data) return {'success': True} elif command.has_key('get'): - fields = command['get'] - instance = f.get(**fields) + fields = command['get'] + instance = f.get(**fields) jc = dict_datetimeflatten(instance) return {'success': True, 'instance': jc} elif command.has_key('update'): if not f.is_valid(): return {'success':False, 'errors': builderrors(f)} - instance = f.save(force_update=True) - fields = command['update'] + instance = f.save(force_update=True) + fields = command['update'] jc = json_convert([instance], fields=fields)[0] return {'success': True, 'instance': jc} @@ -227,7 +227,7 @@ def __process(self, request, params, command=None): if not f.is_valid(): return {'success':False, 'errors': builderrors(f)} instance = f.save() # XXX: if you want more, over-ride save. - fields = command['save'] + fields = command['save'] jc = json_convert([instance], fields=fields)[0] return {'success': True, 'instance': jc} diff --git a/examples/misc/djangowanted/wanted/views.py b/examples/misc/djangowanted/wanted/views.py index c863b0ef3..8cd7e07e8 100644 --- a/examples/misc/djangowanted/wanted/views.py +++ b/examples/misc/djangowanted/wanted/views.py @@ -25,7 +25,7 @@ def index(request, path=None): try: p = Page.objects.get(name=path) except Page.DoesNotExist: - p = None + p = None if not p and path == 'index': return render_to_response('index.html', {'title':'', 'noscript':''}) args = {'title': p.name, diff --git a/examples/misc/djangoweb/media/Email.py b/examples/misc/djangoweb/media/Email.py index 78915c417..eeb3776ed 100644 --- a/examples/misc/djangoweb/media/Email.py +++ b/examples/misc/djangoweb/media/Email.py @@ -35,13 +35,13 @@ def __init__(self, **kwargs): self.message = TextArea() self.message.setCharacterWidth(60) self.message.setVisibleLines(15) - + self.button_py = Button("Send", self) buttons = HorizontalPanel() buttons.add(self.button_py) buttons.setSpacing(8) - + panel.add(HTML("Subject:")) panel.add(self.subject) panel.add(HTML("From:")) @@ -50,7 +50,7 @@ def __init__(self, **kwargs): panel.add(self.message) panel.add(buttons) panel.add(self.status) - + def onClick(self, sender): self.status.setText(self.TEXT_WAITING) text = self.message.getText() diff --git a/examples/misc/djangoweb/media/Popups.py b/examples/misc/djangoweb/media/Popups.py index 29efc737c..4ab4c1687 100644 --- a/examples/misc/djangoweb/media/Popups.py +++ b/examples/misc/djangoweb/media/Popups.py @@ -10,18 +10,18 @@ class FileDialog(DialogBox): def __init__(self, url): DialogBox.__init__(self) self.setText("Upload Files") - + iframe = Frame(url) closeButton = Button("Close", self) msg = HTML("
Upload files, here. Please avoid spaces in file names.
(rename the file before uploading)
", True) dock = DockPanel() dock.setSpacing(4) - + dock.add(closeButton, DockPanel.SOUTH) dock.add(msg, DockPanel.NORTH) dock.add(iframe, DockPanel.CENTER) - + dock.setCellHorizontalAlignment(closeButton, HasAlignment.ALIGN_RIGHT) dock.setCellWidth(iframe, "100%") dock.setWidth("100%") diff --git a/examples/misc/djangoweb/media/WebPage.py b/examples/misc/djangoweb/media/WebPage.py index 9d46203ce..43f781842 100644 --- a/examples/misc/djangoweb/media/WebPage.py +++ b/examples/misc/djangoweb/media/WebPage.py @@ -56,7 +56,7 @@ def onHistoryChanged(self, token): self.remote.getPageByName(token, self) def setPage(self, ref): - + htp = self.pages[ref] if htp == self.current_page: return diff --git a/examples/misc/djangoweb/media/WebPageEdit.py b/examples/misc/djangoweb/media/WebPageEdit.py index 13e789ee8..10f39db4c 100644 --- a/examples/misc/djangoweb/media/WebPageEdit.py +++ b/examples/misc/djangoweb/media/WebPageEdit.py @@ -18,8 +18,8 @@ fileedit_url = '/fckeditor/editor/filemanager/browser/default/browser.html?Connector=/fckeditor%2Feditor%2Ffilemanager%2Fconnectors%2Fpy%2Fconnector.py' # good grieeef, could this get any longer?? -from HTMLDialog import HTMLDialog -from Popups import FileDialog +from HTMLDialog import HTMLDialog +from Popups import FileDialog class WebPageEdit(Composite): def __init__(self, sink): @@ -45,7 +45,7 @@ def __init__(self, sink): self.todoList.addClickListener(self) self.fDialogButton = Button("Upload Files", self) - + self.status = HTML() panel.add(HTML("Status:")) @@ -137,8 +137,8 @@ def onRemoteResponse(self, response, request_info): self.todoTextName.setText(item['fields']['name']) self.todoTextArea.setHTML(item['fields']['text']) - elif (request_info.method == 'getPages' or - request_info.method == 'addPage' or + elif (request_info.method == 'getPages' or + request_info.method == 'addPage' or request_info.method == 'deletePage'): self.status.setHTML(self.status.getText() + "HERE!") self.todoList.clear() diff --git a/examples/misc/djangoweb/webpages/jsonrpc.py b/examples/misc/djangoweb/webpages/jsonrpc.py index b5fa5d929..337bdbe79 100644 --- a/examples/misc/djangoweb/webpages/jsonrpc.py +++ b/examples/misc/djangoweb/webpages/jsonrpc.py @@ -31,10 +31,10 @@ def error(id, code, message): class JSONRPCService: def __init__(self, method_map=None): self.method_map = method_map or {} - + def add_method(self, name, method): self.method_map[name] = method - + def __call__(self, request, extra=None): # We do not yet support GET requests, something pyjamas does # not use anyways. @@ -58,7 +58,7 @@ def __call__(self, request, extra=None): def jsonremote(service): """Make JSONRPCService a decorator so that you can write : - + from jsonrpc import JSONRPCService chatservice = JSONRPCService() @@ -96,7 +96,7 @@ def remotify(func): # (r'^formsservice/$', 'djangoapp.views.processor'), -from django import forms +from django import forms def builderrors(form): d = {} diff --git a/examples/misc/djangoweb/webpages/views.py b/examples/misc/djangoweb/webpages/views.py index 66f61e550..584650094 100644 --- a/examples/misc/djangoweb/webpages/views.py +++ b/examples/misc/djangoweb/webpages/views.py @@ -1,7 +1,7 @@ # Create your views here. from jsonrpc import * -from djangoweb.webpages.models import Page +from djangoweb.webpages.models import Page from django.template import loader from django.shortcuts import render_to_response from django.template import RequestContext, Template diff --git a/examples/misc/flaskexamples/doc/do_it.py b/examples/misc/flaskexamples/doc/do_it.py index c2383e3c1..738212f24 100644 --- a/examples/misc/flaskexamples/doc/do_it.py +++ b/examples/misc/flaskexamples/doc/do_it.py @@ -9,7 +9,7 @@ for line in infile: line = line.rstrip("\n").rstrip() if(line.startswith(".. ")): - if(line.startswith(".. note::")): + if(line.startswith(".. note::")): print >> ofile, line continue @@ -36,7 +36,7 @@ print >> sed_file, "#!/usr/bin/sed -f" for k,v in link_subs.iteritems(): print >> sed_file, "s:%s:%s:g" % (k, v) - + #.. Documentation master file to be processed using sphinx diff --git a/examples/misc/flaskexamples/flaskcelery/FLASKCELERYExample.py b/examples/misc/flaskexamples/flaskcelery/FLASKCELERYExample.py index 3564f9a14..cc81d0dae 100644 --- a/examples/misc/flaskexamples/flaskcelery/FLASKCELERYExample.py +++ b/examples/misc/flaskexamples/flaskcelery/FLASKCELERYExample.py @@ -14,9 +14,9 @@ class LabelTimer(Timer, Label): - __doc__ = """The timer in this demo is a subclass of Timer that + __doc__ = """The timer in this demo is a subclass of Timer that implements a repeated check of the result from a Celery worker until - it is + it is The default is for the application to check every second. """ @@ -72,7 +72,7 @@ def onRemoteError(self, code, errobj, request_info): self.cancel() code = errobj['code'] Label.setText(self, "JSONRPC Error %s: %s" % (code, message)) - + class JSONRPCExample: def onModuleLoad(self): @@ -83,13 +83,13 @@ def onModuleLoad(self): self.METHOD_UPPERCASE = "UPPERCASE" self.METHOD_LOWERCASE = "lowercase" self.METHOD_NONEXISTANT = "Non existant" - self.methods = [self.METHOD_ECHO, self.METHOD_REVERSE, - self.METHOD_UPPERCASE, self.METHOD_LOWERCASE, + self.methods = [self.METHOD_ECHO, self.METHOD_REVERSE, + self.METHOD_UPPERCASE, self.METHOD_LOWERCASE, self.METHOD_NONEXISTANT] self.remote_php = EchoServicePHP() self.remote_py = [ - EchoServicePython(), + EchoServicePython(), EchoServicePython(server="flask"), EchoServicePython(server="flask", flask_view_type="class"), EchoServicePython(server="flask", flask_view_type="celery"), @@ -107,7 +107,7 @@ def onModuleLoad(self): """) self.text_area.setCharacterWidth(80) self.text_area.setVisibleLines(8) - + self.method_list = ListBox() self.method_list.setName("hello") self.method_list.setVisibleItemCount(1) @@ -135,7 +135,7 @@ def onModuleLoad(self): buttons.add(python_buttons[i]) self.python_buttons[python_buttons[i]] = self.remote_py[i] buttons.setSpacing(8) - + info = """

JSON-RPC Example

This example demonstrates the calling of server services with JSON-RPC. @@ -143,14 +143,14 @@ def onModuleLoad(self):

Enter some text below, and press a button to send the text to an Echo service on your server. An echo service simply sends the exact same text back that it receives.

""" - + panel = VerticalPanel() panel.add(HTML(info)) panel.add(self.text_area) panel.add(method_panel) panel.add(buttons) panel.add(self.status) - + RootPanel().add(panel) def onClick(self, sender): @@ -202,7 +202,7 @@ def onRemoteError(self, code, errobj, request_info): # } message = errobj['message'] if code != 0: - self.status.setText("HTTP error %d: %s" % + self.status.setText("HTTP error %d: %s" % (code, message)) else: code = errobj['code'] diff --git a/examples/misc/flaskexamples/flaskcelery/flask_source/celery_tasks.py b/examples/misc/flaskexamples/flaskcelery/flask_source/celery_tasks.py index da920e63b..608ae8eed 100644 --- a/examples/misc/flaskexamples/flaskcelery/flask_source/celery_tasks.py +++ b/examples/misc/flaskexamples/flaskcelery/flask_source/celery_tasks.py @@ -9,4 +9,4 @@ @celery.task(name="celery_echo") def celery_echo(mth, txt): - return echo(mth,txt) + return echo(mth,txt) diff --git a/examples/misc/flaskexamples/flaskcelery/flask_source/celery_views.py b/examples/misc/flaskexamples/flaskcelery/flask_source/celery_views.py index 5d9bc4839..2a71aa311 100644 --- a/examples/misc/flaskexamples/flaskcelery/flask_source/celery_views.py +++ b/examples/misc/flaskexamples/flaskcelery/flask_source/celery_views.py @@ -1,4 +1,4 @@ -from flask import request +from flask import request from method_views import JSONRPCView from celery_tasks import celery_echo @@ -6,21 +6,21 @@ class CeleryEchoView(JSONRPCView): """ - This class setup the allowed methods for this view, and defines the - RPC handling. It uses Flask-Celery to asynchronously execute the - remote procedure (RP) on the server (from the client's point of view it is + This class setup the allowed methods for this view, and defines the + RPC handling. It uses Flask-Celery to asynchronously execute the + remote procedure (RP) on the server (from the client's point of view it is already asynchronous). """ rpc_methods = ["echo", "reverse", "uppercase", "lowercase", "get_result"] - + def echo(self): """ - This function either initiates an echo and returns a Celery task id + This function either initiates an echo and returns a Celery task id OR it will look in the JSON request for a task id. """ - - # We are expecting a dictionary or a list. If it is a list, we - # will echo the first element. If it is a dictionary, we are + + # We are expecting a dictionary or a list. If it is a list, we + # will echo the first element. If it is a dictionary, we are # assuming it will have the key "task_id" with a valid Celery # task id. if(request.json["method"] == "get_result"): @@ -34,8 +34,8 @@ def echo(self): if(res.state == "FAILURE"): msg = "Internal JSON-RPC Error" self.json_response["error"] = {"code":-32602, "message":msg} - return - + return + self.json_response["result"] = \ {"task_id":task_id, "state":res.state} if(res.state == "SUCCESS"): @@ -44,7 +44,7 @@ def echo(self): msg = "Invalid Request: for get_result, parameters is " msg += "required to be a dictionary" self.json_response["error"] = {"code":-32602, "message":msg} - + elif(isinstance(self.params, (list,))): # countdown for 5 seconds so we have a few requests from pyjamas # for a result diff --git a/examples/misc/flaskexamples/flaskcelery/flask_source/celeryconfig.py b/examples/misc/flaskexamples/flaskcelery/flask_source/celeryconfig.py index c304a6183..2d648af94 100644 --- a/examples/misc/flaskexamples/flaskcelery/flask_source/celeryconfig.py +++ b/examples/misc/flaskexamples/flaskcelery/flask_source/celeryconfig.py @@ -3,8 +3,8 @@ BROKER_USER = "your_celery_user_here" BROKER_PASSWORD = "your_password_here" -# For now we use the AMQP backend to store task metadata and return values, -# but one may wish to store it somewhere that is persistent rather than send +# For now we use the AMQP backend to store task metadata and return values, +# but one may wish to store it somewhere that is persistent rather than send # it as an AMQP message. CELERY_RESULT_BACKEND = "amqp" #CELERY_RESULT_BACKEND = "redis" diff --git a/examples/misc/flaskexamples/flaskcelery/flask_source/manage_celery.py b/examples/misc/flaskexamples/flaskcelery/flask_source/manage_celery.py index f13f2ec50..ce8185e11 100644 --- a/examples/misc/flaskexamples/flaskcelery/flask_source/manage_celery.py +++ b/examples/misc/flaskexamples/flaskcelery/flask_source/manage_celery.py @@ -20,5 +20,5 @@ # To start a celeryd (celery worker) use: # "python manage_celery.py celeryd --loglevel=INFO" # To start a flask server on localhost:5000 use: - # "python manage_celery.py runserver" + # "python manage_celery.py runserver" manager.run() diff --git a/examples/misc/flaskexamples/flaskcelery/flask_source/method_views.py b/examples/misc/flaskexamples/flaskcelery/flask_source/method_views.py index 5d5511768..4d6429e62 100644 --- a/examples/misc/flaskexamples/flaskcelery/flask_source/method_views.py +++ b/examples/misc/flaskexamples/flaskcelery/flask_source/method_views.py @@ -6,16 +6,16 @@ class JSONRPCView(MethodView): """ - This class provides one way of handling JSON-RPC via Flask. + This class provides one way of handling JSON-RPC via Flask. We allow for the client to use OPTIONS to pre-flight the POST request. - + Note:: - + This class is experimental and tries to follow the JSON-RPC 2.0 almost standard (it supposedly isn't a standard yet). - + Errors - + code message meaning -32700 Parse error Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text. @@ -26,23 +26,23 @@ class JSONRPCView(MethodView): -32099 to -32000 Server error Reserved for implementation-defined server-errors. """ - request_fields = {"required":["jsonrpc", "method"], + request_fields = {"required":["jsonrpc", "method"], "optional":["id", "params"]} - + def options(self): """ Handle browsers that prefight a "complex" POST with OPTIONS """ resp = make_response("", 200) - # Just parrot the origin back for now. - # If they don't give one, they don't get one. + # Just parrot the origin back for now. + # If they don't give one, they don't get one. resp.headers["Access-Control-Allow-Origin"] = \ request.headers.get("Origin", "*") # No need for GET with RPC resp.headers["Access-Control-Allow-Methods"] = "POST, OPTIONS" # Allow a max age of one day resp.headers["Access-Control-Max-Age"] = 24 * 3600 - # Chrome wants this; one may choose to support additional custom + # Chrome wants this; one may choose to support additional custom # headers in a actual application. resp.headers["Access-Control-Allow-Headers"] = "Content-Type" return resp @@ -55,42 +55,42 @@ def post(self): # If "id" is not provided, then we are not supposed to return any type # of response to the client as it doesn't care about the response. # Therefore, we don't care either and won't waste any more resources. - if(not "id" in request.json): + if(not "id" in request.json): return - + self.json_response = {"jsonrpc":"2.0"} self.error = self._is_jsonrpc_request() if(not self.error): self.error = self._check_method_and_params() - + self.json_response["id"] = request.json["id"] if(self.error): self.json_response["error"] = self.error return self.make_post_response() - - # pass control to the subclass - self.echo() - + + # pass control to the subclass + self.echo() + return self.make_post_response() def make_post_response(self): resp = jsonify(self.json_response) - # Just parrot the origin back for now. If they don't give one, they - # don't get one. + # Just parrot the origin back for now. If they don't give one, they + # don't get one. resp.headers["Access-Control-Allow-Origin"] = \ request.headers.get("Origin", "*") return resp - + def _is_jsonrpc_request(self): """ Check if the request is valid json-rpc 2.0 """ - + if(not request.content_type == "application/json-rpc"): msg = "Invalid Request: The server received an " msg += "invalid content_type" return {"code":-32600, "message":msg} - + for f in self.request_fields["required"]: if(not f in request.json): msg = "Invalid Request: The JSON sent is not a valid " @@ -99,26 +99,26 @@ def _is_jsonrpc_request(self): if(request.json["jsonrpc"] != "2.0"): msg = "Invalid Request: The JSON RPC version must be 2.0" return {"code":-32600, "message":msg} - + return {} def _check_method_and_params(self): """ Check if the method in the request is one of the supported methods. - + Note:: Do not rename self.rpc_methods to self.methods as self.methods is reserved for the HTTP methods allowed for this class. """ self.method = request.json["method"].lower() if(self.method not in self.rpc_methods): - msg = "The method %s does not exist / is not available." + msg = "The method %s does not exist / is not available." return {"code":-32601, "message":msg % (request.json["method"])} - + self.params = request.json.get("params") if(not self.params): msg = "Invalid Request: parameters are required" return {"code":-32602, "message":msg} - + return None def echo(self): @@ -127,11 +127,11 @@ def echo(self): class JSONEchoView(JSONRPCView): """ - This class setup the allowed methods for this view, and defines the + This class setup the allowed methods for this view, and defines the RPC handling """ rpc_methods = ["echo", "reverse", "uppercase", "lowercase"] - + def echo(self): # Assume the JSON params field is a list of length at least one rv = echo(self.method, self.params[0]) diff --git a/examples/misc/flaskexamples/flaskcelery/public/services/EchoService.py b/examples/misc/flaskexamples/flaskcelery/public/services/EchoService.py index e9be35ede..07ecf0e00 100644 --- a/examples/misc/flaskexamples/flaskcelery/public/services/EchoService.py +++ b/examples/misc/flaskexamples/flaskcelery/public/services/EchoService.py @@ -22,4 +22,4 @@ def lowercase(self, msg): # this is if JSONService.py is run from mod_python: # rename .htaccess.mod_python to .htaccess to activate, # and restart Apache2 - from jsonrpc.apacheServiceHandler import handler + from jsonrpc.apacheServiceHandler import handler diff --git a/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/__init__.py b/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/__init__.py index c3cf84ba9..05bfcac75 100644 --- a/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/__init__.py +++ b/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/__init__.py @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from threading import Event, Lock @@ -28,29 +28,29 @@ from json import JSONDecoder, JSONEncoder -class JSONRPCEncoder(JSONEncoder): - def default(self, obj): - if isinstance(obj, JSONRPCError): - return obj.__class__.__name__ +class JSONRPCEncoder(JSONEncoder): + def default(self, obj): + if isinstance(obj, JSONRPCError): + return obj.__class__.__name__ else: return JSONEncoder.default(self, obj) class Timeout(Exception): pass - + class ResponseEvent: """Event which is fired when the response is returned for a request. - - For each request sent this event is created. + + For each request sent this event is created. An application can wait for the event to create a blocking request. """ def __init__(self): self.__evt = Event() - + def waiting(self): return not self.__evt.isSet() - + def waitForResponse(self, timeOut=None): """blocks until the response arrived or timeout is reached.""" self.__evt.wait(timeOut) @@ -61,12 +61,12 @@ def waitForResponse(self, timeOut=None): raise Exception(self.response["error"]) else: return self.response["result"] - + def handleResponse(self, resp): self.response = resp self.__evt.set() - - + + class SimpleMessageHandler: def __init__(self, DecoderClass=JSONDecoder, EncoderClass=JSONRPCEncoder, messageDelimiter=""): self.decoder = DecoderClass() @@ -75,16 +75,16 @@ def __init__(self, DecoderClass=JSONDecoder, EncoderClass=JSONRPCEncoder, messa self.respEvents={} self.respLock = Lock() self.messageDelimiter=messageDelimiter - + def close(self): pass - + def send(self, data): pass - + def sendMessage(self, msg): self.send(self.encoder.encode(msg) + self.messageDelimiter) - + def handlePartialData(self, data): data = self.partialData + data.replace("\r","").replace("\n", "") msgs=[] @@ -95,32 +95,32 @@ def handlePartialData(self, data): try: (obj, pos) = self.decoder.raw_decode(data) data = data[pos:] - msgs.append(obj) + msgs.append(obj) except: break else: break self.partialData = data - + self.handleMessages(msgs) def sendNotify(self, name, args): """sends a notification object to the peer""" self.sendMessage({"method":name, "params": args}) - + def sendRequest(self, name, args): """sends a request to the peer""" (respEvt, id) = self.newResponseEvent() self.sendMessage({"id":id, "method":name, "params": args}) return respEvt - + def sendResponse(self, id, result, error): """sends a response to the peer""" self.sendMessage({"result":result, "error": error, "id":id}) - + def newResponseEvent(self): """creates a response event and adds it to a waiting list - When the reponse arrives it will be removed from the list. + When the reponse arrives it will be removed from the list. """ respEvt = ResponseEvent() self.respLock.acquire() @@ -128,36 +128,36 @@ def newResponseEvent(self): self.respEvents[eid] = respEvt self.respLock.release() return (respEvt,eid) - + def handleMessages(self, msgs): for msg in msgs: if msg.has_key("method") and msg.has_key("params"): if msg.has_key("id"): if msg["id"]: - self.handleRequest(msg) + self.handleRequest(msg) else: self.handleNotification(msg) else: self.handleNotification(msg) elif msg.has_key("result") and msg.has_key("error"): self.handleResponse(msg) - else:#unknown object + else:#unknown object self.sendResponse(None, InvalidJSONMessage()) self.close() - + def handleResponse(self, resp): """handles a response by fireing the response event for the response coming in""" id=resp["id"] evt = self.respEvents[id] del(self.respEvents[id]) evt.handleResponse(resp) - + def handleRequest(self, request): pass def handleNotification(self, notification): pass - - + + import re NameAllowedRegExp=re.compile("^[a-zA-Z]\w*$") def nameAllowed(name): @@ -167,7 +167,7 @@ def nameAllowed(name): return 1 else: return 0 - + def getMethodByName(obj, name): """searches for an object with the name given inside the object given. @@ -176,7 +176,7 @@ def getMethodByName(obj, name): try:#to get a method by asking the service obj = obj._getMethodByName(name) except: - #assumed a childObject is ment + #assumed a childObject is ment #split the name from objName.childObjName... -> [objName, childObjName, ...] #and get all objects up to the last in list with name checking from the service object names = name.split(".") @@ -185,9 +185,9 @@ def getMethodByName(obj, name): obj = getattr(obj, name) else: raise MethodNameNotAllowed() - - return obj - + + return obj + class SimpleServiceHandler(SimpleMessageHandler): @@ -198,20 +198,20 @@ def __init__(self, service, DecoderClass=JSONDecoder, EncoderClass=JSONRPCEncode service._newConnection(self) except: pass - + def close(self): try: self.service._closingConnection(self) except: pass - + def handleRequest(self, req): """handles a request by calling the appropriete method the service exposes""" name = req["method"] params = req["params"] id=req["id"] obj=None - try: #to get a callable obj + try: #to get a callable obj obj = getMethodByName(self.service, name) except MethodNameNotAllowed,e: self.sendResponse(id, None, e) @@ -228,17 +228,17 @@ def handleRequest(self, req): except: #error inside the callable object s=getTracebackStr() self.sendResponse(id, None, s) - + def handleNotification(self, req): """handles a notification request by calling the appropriete method the service exposes""" name = req["method"] params = req["params"] - try: #to get a callable obj + try: #to get a callable obj obj = getMethodByName(self.service, name) rslt = obj(*params) except: pass - - - + + + diff --git a/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/apacheServiceHandler.py b/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/apacheServiceHandler.py index e41ab4645..00ac9bd6c 100644 --- a/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/apacheServiceHandler.py +++ b/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/apacheServiceHandler.py @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from mod_python import apache from jsonrpc import SimpleServiceHandler @@ -25,28 +25,28 @@ class ModPyHandler(SimpleServiceHandler): def send(self, data): self.req.write(data) self.req.flush() - + def handle(self, req): self.req = req req.content_type = "text/plain" self.handlePartialData(req.read()) - self.close() + self.close() -from mod_python import apache +from mod_python import apache import os, sys - -def handler(req): + +def handler(req): (modulePath, fileName) = os.path.split(req.filename) (moduleName, ext) = os.path.splitext(fileName) - + if not os.path.exists(os.path.join(modulePath, moduleName + ".py")): return apache.HTTP_NOT_FOUND - + if not modulePath in sys.path: sys.path.insert(0, modulePath) - + module = apache.import_module(moduleName, log=1) - + if hasattr(module, "getService"): service = module.getService() elif hasattr(module, "service"): @@ -55,8 +55,8 @@ def handler(req): service = module.Service() else: return apache.HTTP_SERVICE_UNAVAILABLE - + ModPyHandler(service, messageDelimiter="\n").handle(req) - + return apache.OK - + diff --git a/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/cgihandler.py b/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/cgihandler.py index 1cf586efb..ced1832ec 100644 --- a/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/cgihandler.py +++ b/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/cgihandler.py @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from jsonrpc import SimpleServiceHandler @@ -27,10 +27,10 @@ def __init__(self, service, messageDelimiter="\n"): self.sendData =[] SimpleServiceHandler.__init__(self, service, messageDelimiter=messageDelimiter) - + def send(self, data): self.sendData.append(data) - + def handle(self): try: contLen=int(os.environ['CONTENT_LENGTH']) @@ -38,25 +38,25 @@ def handle(self): except: data = "" #execute the request - self.handlePartialData(data) + self.handlePartialData(data) self.sendReply() self.close() - + def sendReply(self): data = "\n".join(self.sendData) response = "Content-Type: text/plain\n" response += "Content-Length: %d\n\n" % len(data) response += data - + #on windows all \n are converted to \r\n if stdout is a terminal and is not set to binary mode :( #this will then cause an incorrect Content-length. #I have only experienced this problem with apache on Win so far. - if sys.platform == "win32": - import msvcrt + if sys.platform == "win32": + import msvcrt msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) #put out the response sys.stdout.write(response) - - + + def handleCGIRequest(service): CGIHandler(service,messageDelimiter="\n").handle() diff --git a/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/errors.py b/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/errors.py index 597f78010..deaab48d8 100644 --- a/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/errors.py +++ b/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/errors.py @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ class JSONRPCError: @@ -34,8 +34,8 @@ class InvalidMethodParameters(JSONRPCError): pass class MethodNameNotAllowed(JSONRPCError): pass - - + + def getTracebackStr(): import traceback diff --git a/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/http.py b/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/http.py index 42f3c6791..ca19fe02b 100644 --- a/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/http.py +++ b/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/http.py @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from jsonrpc import SimpleServiceHandler @@ -26,9 +26,8 @@ class HTTPClientConnectionHandler(SimpleServiceHandler): def __init__(self, url, service,messageDelimiter=""): self.url = url SimpleServiceHandler.__init__(self, service,messageDelimiter=messageDelimiter) - + def send(self, data): req = urllib2.Request(self.url, data) resp = urllib2.urlopen(req) self.handlePartialData(resp.read()) - \ No newline at end of file diff --git a/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/proxy.py b/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/proxy.py index 6cb7399af..7496b3900 100644 --- a/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/proxy.py +++ b/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/proxy.py @@ -15,20 +15,20 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ - + class PeerObjectProxy(object): """creates a peer object which will send requests to the remote service when invoked.""" def __init__(self, name, conn): self._name = name self._conn = conn - + def notify(self, *args): self._conn.sendNotify(self._name, args) - + def __call__(self, *args): evt = self._conn.sendRequest(self._name, args) return evt.waitForResponse() @@ -40,7 +40,7 @@ def __getattr__(self, name): class PeerProxy: def __init__(self, connectionHandler): self._connectionHandler = connectionHandler - + def __getattr__(self, name): return PeerObjectProxy(name, self._connectionHandler) @@ -55,14 +55,14 @@ def __init__(self, url, localService=None, messageDelimiter=""): from jsonrpc.socketserver import SocketServiceHandler import socket from threading import Thread - + (host, port)= m.groups() port = int(port) - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) conn = SocketServiceHandler(s, localService,messageDelimiter=messageDelimiter) PeerProxy.__init__(self, conn) - + t=Thread(target=conn.receiveForever) t.setDaemon(True) t.start() @@ -71,6 +71,6 @@ def __init__(self, url, localService=None, messageDelimiter=""): conn= HTTPClientConnectionHandler(url, localService,messageDelimiter=messageDelimiter) PeerProxy.__init__(self, conn) - + diff --git a/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/socketserver.py b/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/socketserver.py index 7c9d44f86..2b52ca42c 100644 --- a/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/socketserver.py +++ b/examples/misc/flaskexamples/flaskcelery/public/services/jsonrpc/socketserver.py @@ -15,19 +15,19 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from jsonrpc import SimpleServiceHandler import socket from threading import Thread - - + + class SocketServiceHandler(SimpleServiceHandler): def __init__(self, socket, service, messageDelimiter=""): self.socket = socket SimpleServiceHandler.__init__(self, service, messageDelimiter=messageDelimiter) - + def receiveForever(self): while 1: try: @@ -39,12 +39,12 @@ def receiveForever(self): if self.socket: self.close() return - else: + else: self.handlePartialData(data) - + def send(self, data): self.socket.send(data) - + def close(self): SimpleServiceHandler.close(self) if self.socket: @@ -53,7 +53,7 @@ def close(self): self.socket = None except: pass - + class TCPServiceServer: @@ -61,22 +61,22 @@ def __init__(self, service, ConnectionHandler = SocketServiceHandler, messageDel self.service = service self.ConnectionHandler = ConnectionHandler self.messageDelimiter=messageDelimiter - + def serve(self, address): - self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.socket.bind(address) + self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.socket.bind(address) self.socket.listen(5) print "serving", self.socket while 1: (conn,addr) = self.socket.accept() self.acceptConnection(conn) - + def acceptConnection(self, conn): self.handleConnection(conn) - + def handleConnection(self, conn): self.ConnectionHandler(conn, self.service, messageDelimiter=self.messageDelimiter).receiveForever() - + class ThreadingMixin: @@ -87,5 +87,5 @@ def acceptConnection(self, conn): class ThreadedTCPServiceServer(ThreadingMixin, TCPServiceServer): pass - - + + diff --git a/examples/misc/flaskexamples/flaskcors/Flask_JSONRPC_CORS.py b/examples/misc/flaskexamples/flaskcors/Flask_JSONRPC_CORS.py index cbc19d8cf..d206f75b8 100644 --- a/examples/misc/flaskexamples/flaskcors/Flask_JSONRPC_CORS.py +++ b/examples/misc/flaskexamples/flaskcors/Flask_JSONRPC_CORS.py @@ -19,13 +19,13 @@ def onModuleLoad(self): self.METHOD_UPPERCASE = "UPPERCASE" self.METHOD_LOWERCASE = "lowercase" self.METHOD_NONEXISTANT = "Non existant" - self.methods = [self.METHOD_ECHO, self.METHOD_REVERSE, - self.METHOD_UPPERCASE, self.METHOD_LOWERCASE, + self.methods = [self.METHOD_ECHO, self.METHOD_REVERSE, + self.METHOD_UPPERCASE, self.METHOD_LOWERCASE, self.METHOD_NONEXISTANT] self.remote_php = EchoServicePHP() self.remote_py = [ - EchoServicePython(), + EchoServicePython(), EchoServicePython(server="flask"), ] @@ -40,7 +40,7 @@ def onModuleLoad(self): """) self.text_area.setCharacterWidth(80) self.text_area.setVisibleLines(8) - + self.method_list = ListBox() self.method_list.setName("hello") self.method_list.setVisibleItemCount(1) @@ -66,7 +66,7 @@ def onModuleLoad(self): buttons.add(python_buttons[i]) self.python_buttons[python_buttons[i]] = self.remote_py[i] buttons.setSpacing(8) - + info = """

JSON-RPC Example

This example demonstrates the calling of server services with JSON-RPC. @@ -74,14 +74,14 @@ def onModuleLoad(self):

Enter some text below, and press a button to send the text to an Echo service on your server. An echo service simply sends the exact same text back that it receives.

""" - + panel = VerticalPanel() panel.add(HTML(info)) panel.add(self.text_area) panel.add(method_panel) panel.add(buttons) panel.add(self.status) - + RootPanel().add(panel) def onClick(self, sender): @@ -130,7 +130,7 @@ def onRemoteError(self, code, errobj, request_info): # } message = errobj['message'] if code != 0: - self.status.setText("HTTP error %d: %s" % + self.status.setText("HTTP error %d: %s" % (code, message)) else: code = errobj['code'] diff --git a/examples/misc/flaskexamples/flaskcors/public/services/EchoService.py b/examples/misc/flaskexamples/flaskcors/public/services/EchoService.py index e9be35ede..07ecf0e00 100644 --- a/examples/misc/flaskexamples/flaskcors/public/services/EchoService.py +++ b/examples/misc/flaskexamples/flaskcors/public/services/EchoService.py @@ -22,4 +22,4 @@ def lowercase(self, msg): # this is if JSONService.py is run from mod_python: # rename .htaccess.mod_python to .htaccess to activate, # and restart Apache2 - from jsonrpc.apacheServiceHandler import handler + from jsonrpc.apacheServiceHandler import handler diff --git a/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/__init__.py b/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/__init__.py index c3cf84ba9..05bfcac75 100644 --- a/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/__init__.py +++ b/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/__init__.py @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from threading import Event, Lock @@ -28,29 +28,29 @@ from json import JSONDecoder, JSONEncoder -class JSONRPCEncoder(JSONEncoder): - def default(self, obj): - if isinstance(obj, JSONRPCError): - return obj.__class__.__name__ +class JSONRPCEncoder(JSONEncoder): + def default(self, obj): + if isinstance(obj, JSONRPCError): + return obj.__class__.__name__ else: return JSONEncoder.default(self, obj) class Timeout(Exception): pass - + class ResponseEvent: """Event which is fired when the response is returned for a request. - - For each request sent this event is created. + + For each request sent this event is created. An application can wait for the event to create a blocking request. """ def __init__(self): self.__evt = Event() - + def waiting(self): return not self.__evt.isSet() - + def waitForResponse(self, timeOut=None): """blocks until the response arrived or timeout is reached.""" self.__evt.wait(timeOut) @@ -61,12 +61,12 @@ def waitForResponse(self, timeOut=None): raise Exception(self.response["error"]) else: return self.response["result"] - + def handleResponse(self, resp): self.response = resp self.__evt.set() - - + + class SimpleMessageHandler: def __init__(self, DecoderClass=JSONDecoder, EncoderClass=JSONRPCEncoder, messageDelimiter=""): self.decoder = DecoderClass() @@ -75,16 +75,16 @@ def __init__(self, DecoderClass=JSONDecoder, EncoderClass=JSONRPCEncoder, messa self.respEvents={} self.respLock = Lock() self.messageDelimiter=messageDelimiter - + def close(self): pass - + def send(self, data): pass - + def sendMessage(self, msg): self.send(self.encoder.encode(msg) + self.messageDelimiter) - + def handlePartialData(self, data): data = self.partialData + data.replace("\r","").replace("\n", "") msgs=[] @@ -95,32 +95,32 @@ def handlePartialData(self, data): try: (obj, pos) = self.decoder.raw_decode(data) data = data[pos:] - msgs.append(obj) + msgs.append(obj) except: break else: break self.partialData = data - + self.handleMessages(msgs) def sendNotify(self, name, args): """sends a notification object to the peer""" self.sendMessage({"method":name, "params": args}) - + def sendRequest(self, name, args): """sends a request to the peer""" (respEvt, id) = self.newResponseEvent() self.sendMessage({"id":id, "method":name, "params": args}) return respEvt - + def sendResponse(self, id, result, error): """sends a response to the peer""" self.sendMessage({"result":result, "error": error, "id":id}) - + def newResponseEvent(self): """creates a response event and adds it to a waiting list - When the reponse arrives it will be removed from the list. + When the reponse arrives it will be removed from the list. """ respEvt = ResponseEvent() self.respLock.acquire() @@ -128,36 +128,36 @@ def newResponseEvent(self): self.respEvents[eid] = respEvt self.respLock.release() return (respEvt,eid) - + def handleMessages(self, msgs): for msg in msgs: if msg.has_key("method") and msg.has_key("params"): if msg.has_key("id"): if msg["id"]: - self.handleRequest(msg) + self.handleRequest(msg) else: self.handleNotification(msg) else: self.handleNotification(msg) elif msg.has_key("result") and msg.has_key("error"): self.handleResponse(msg) - else:#unknown object + else:#unknown object self.sendResponse(None, InvalidJSONMessage()) self.close() - + def handleResponse(self, resp): """handles a response by fireing the response event for the response coming in""" id=resp["id"] evt = self.respEvents[id] del(self.respEvents[id]) evt.handleResponse(resp) - + def handleRequest(self, request): pass def handleNotification(self, notification): pass - - + + import re NameAllowedRegExp=re.compile("^[a-zA-Z]\w*$") def nameAllowed(name): @@ -167,7 +167,7 @@ def nameAllowed(name): return 1 else: return 0 - + def getMethodByName(obj, name): """searches for an object with the name given inside the object given. @@ -176,7 +176,7 @@ def getMethodByName(obj, name): try:#to get a method by asking the service obj = obj._getMethodByName(name) except: - #assumed a childObject is ment + #assumed a childObject is ment #split the name from objName.childObjName... -> [objName, childObjName, ...] #and get all objects up to the last in list with name checking from the service object names = name.split(".") @@ -185,9 +185,9 @@ def getMethodByName(obj, name): obj = getattr(obj, name) else: raise MethodNameNotAllowed() - - return obj - + + return obj + class SimpleServiceHandler(SimpleMessageHandler): @@ -198,20 +198,20 @@ def __init__(self, service, DecoderClass=JSONDecoder, EncoderClass=JSONRPCEncode service._newConnection(self) except: pass - + def close(self): try: self.service._closingConnection(self) except: pass - + def handleRequest(self, req): """handles a request by calling the appropriete method the service exposes""" name = req["method"] params = req["params"] id=req["id"] obj=None - try: #to get a callable obj + try: #to get a callable obj obj = getMethodByName(self.service, name) except MethodNameNotAllowed,e: self.sendResponse(id, None, e) @@ -228,17 +228,17 @@ def handleRequest(self, req): except: #error inside the callable object s=getTracebackStr() self.sendResponse(id, None, s) - + def handleNotification(self, req): """handles a notification request by calling the appropriete method the service exposes""" name = req["method"] params = req["params"] - try: #to get a callable obj + try: #to get a callable obj obj = getMethodByName(self.service, name) rslt = obj(*params) except: pass - - - + + + diff --git a/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/apacheServiceHandler.py b/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/apacheServiceHandler.py index e41ab4645..00ac9bd6c 100644 --- a/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/apacheServiceHandler.py +++ b/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/apacheServiceHandler.py @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from mod_python import apache from jsonrpc import SimpleServiceHandler @@ -25,28 +25,28 @@ class ModPyHandler(SimpleServiceHandler): def send(self, data): self.req.write(data) self.req.flush() - + def handle(self, req): self.req = req req.content_type = "text/plain" self.handlePartialData(req.read()) - self.close() + self.close() -from mod_python import apache +from mod_python import apache import os, sys - -def handler(req): + +def handler(req): (modulePath, fileName) = os.path.split(req.filename) (moduleName, ext) = os.path.splitext(fileName) - + if not os.path.exists(os.path.join(modulePath, moduleName + ".py")): return apache.HTTP_NOT_FOUND - + if not modulePath in sys.path: sys.path.insert(0, modulePath) - + module = apache.import_module(moduleName, log=1) - + if hasattr(module, "getService"): service = module.getService() elif hasattr(module, "service"): @@ -55,8 +55,8 @@ def handler(req): service = module.Service() else: return apache.HTTP_SERVICE_UNAVAILABLE - + ModPyHandler(service, messageDelimiter="\n").handle(req) - + return apache.OK - + diff --git a/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/cgihandler.py b/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/cgihandler.py index 1cf586efb..ced1832ec 100644 --- a/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/cgihandler.py +++ b/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/cgihandler.py @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from jsonrpc import SimpleServiceHandler @@ -27,10 +27,10 @@ def __init__(self, service, messageDelimiter="\n"): self.sendData =[] SimpleServiceHandler.__init__(self, service, messageDelimiter=messageDelimiter) - + def send(self, data): self.sendData.append(data) - + def handle(self): try: contLen=int(os.environ['CONTENT_LENGTH']) @@ -38,25 +38,25 @@ def handle(self): except: data = "" #execute the request - self.handlePartialData(data) + self.handlePartialData(data) self.sendReply() self.close() - + def sendReply(self): data = "\n".join(self.sendData) response = "Content-Type: text/plain\n" response += "Content-Length: %d\n\n" % len(data) response += data - + #on windows all \n are converted to \r\n if stdout is a terminal and is not set to binary mode :( #this will then cause an incorrect Content-length. #I have only experienced this problem with apache on Win so far. - if sys.platform == "win32": - import msvcrt + if sys.platform == "win32": + import msvcrt msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) #put out the response sys.stdout.write(response) - - + + def handleCGIRequest(service): CGIHandler(service,messageDelimiter="\n").handle() diff --git a/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/errors.py b/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/errors.py index 597f78010..deaab48d8 100644 --- a/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/errors.py +++ b/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/errors.py @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ class JSONRPCError: @@ -34,8 +34,8 @@ class InvalidMethodParameters(JSONRPCError): pass class MethodNameNotAllowed(JSONRPCError): pass - - + + def getTracebackStr(): import traceback diff --git a/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/http.py b/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/http.py index 42f3c6791..ca19fe02b 100644 --- a/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/http.py +++ b/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/http.py @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from jsonrpc import SimpleServiceHandler @@ -26,9 +26,8 @@ class HTTPClientConnectionHandler(SimpleServiceHandler): def __init__(self, url, service,messageDelimiter=""): self.url = url SimpleServiceHandler.__init__(self, service,messageDelimiter=messageDelimiter) - + def send(self, data): req = urllib2.Request(self.url, data) resp = urllib2.urlopen(req) self.handlePartialData(resp.read()) - \ No newline at end of file diff --git a/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/proxy.py b/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/proxy.py index 6cb7399af..7496b3900 100644 --- a/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/proxy.py +++ b/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/proxy.py @@ -15,20 +15,20 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ - + class PeerObjectProxy(object): """creates a peer object which will send requests to the remote service when invoked.""" def __init__(self, name, conn): self._name = name self._conn = conn - + def notify(self, *args): self._conn.sendNotify(self._name, args) - + def __call__(self, *args): evt = self._conn.sendRequest(self._name, args) return evt.waitForResponse() @@ -40,7 +40,7 @@ def __getattr__(self, name): class PeerProxy: def __init__(self, connectionHandler): self._connectionHandler = connectionHandler - + def __getattr__(self, name): return PeerObjectProxy(name, self._connectionHandler) @@ -55,14 +55,14 @@ def __init__(self, url, localService=None, messageDelimiter=""): from jsonrpc.socketserver import SocketServiceHandler import socket from threading import Thread - + (host, port)= m.groups() port = int(port) - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) conn = SocketServiceHandler(s, localService,messageDelimiter=messageDelimiter) PeerProxy.__init__(self, conn) - + t=Thread(target=conn.receiveForever) t.setDaemon(True) t.start() @@ -71,6 +71,6 @@ def __init__(self, url, localService=None, messageDelimiter=""): conn= HTTPClientConnectionHandler(url, localService,messageDelimiter=messageDelimiter) PeerProxy.__init__(self, conn) - + diff --git a/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/socketserver.py b/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/socketserver.py index 7c9d44f86..2b52ca42c 100644 --- a/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/socketserver.py +++ b/examples/misc/flaskexamples/flaskcors/public/services/jsonrpc/socketserver.py @@ -15,19 +15,19 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from jsonrpc import SimpleServiceHandler import socket from threading import Thread - - + + class SocketServiceHandler(SimpleServiceHandler): def __init__(self, socket, service, messageDelimiter=""): self.socket = socket SimpleServiceHandler.__init__(self, service, messageDelimiter=messageDelimiter) - + def receiveForever(self): while 1: try: @@ -39,12 +39,12 @@ def receiveForever(self): if self.socket: self.close() return - else: + else: self.handlePartialData(data) - + def send(self, data): self.socket.send(data) - + def close(self): SimpleServiceHandler.close(self) if self.socket: @@ -53,7 +53,7 @@ def close(self): self.socket = None except: pass - + class TCPServiceServer: @@ -61,22 +61,22 @@ def __init__(self, service, ConnectionHandler = SocketServiceHandler, messageDel self.service = service self.ConnectionHandler = ConnectionHandler self.messageDelimiter=messageDelimiter - + def serve(self, address): - self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.socket.bind(address) + self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.socket.bind(address) self.socket.listen(5) print "serving", self.socket while 1: (conn,addr) = self.socket.accept() self.acceptConnection(conn) - + def acceptConnection(self, conn): self.handleConnection(conn) - + def handleConnection(self, conn): self.ConnectionHandler(conn, self.service, messageDelimiter=self.messageDelimiter).receiveForever() - + class ThreadingMixin: @@ -87,5 +87,5 @@ def acceptConnection(self, conn): class ThreadedTCPServiceServer(ThreadingMixin, TCPServiceServer): pass - - + + diff --git a/examples/misc/flowplayer/fp.py b/examples/misc/flowplayer/fp.py index 0b6277bb6..9ae739413 100644 --- a/examples/misc/flowplayer/fp.py +++ b/examples/misc/flowplayer/fp.py @@ -8,55 +8,55 @@ class FlowPlayerExample: - + def onModuleLoad(self): self.panel = VerticalPanel() self.player = self.getPlayer() - + # Add the Player to the Panel self.panel.add(self.player) RootPanel().add(self.panel) - - + + def getPlayer(self): """ Create a player """ # Url to the flowplayer flashmovie url = 'swf/flowplayer.swf' - + # Create the initial configuration config = Configuration() - + # Add a Content plugin = self.getContentTop() config.addPlugin(plugin) - + # Customize Controls, if controls not added, # default controls will be used plugin = self.getControls() config.addPlugin(plugin) - + # Add the Common-Clip to configuration common_clip = Clip() common_clip.setAttr('autoBuffering', True) common_clip.setAttr('autoPlay', False) config.setCommonClip(common_clip) - + # Set a playlist playlist = self.getPlaylist() config.setPlaylist(playlist) - + # Create the Player Object with the initial configuration #log.debug('Loading Player') player = Player(url, config) - + # Add Listener to the player player.addListener(self) - + return player - - + + def getPlaylist(self): """ Create a playlist @@ -70,8 +70,8 @@ def getPlaylist(self): for clip in playlist: clip.addListener(self) return playlist - - + + def getControls(self): """ Create and configure the Controls Plugin @@ -87,10 +87,10 @@ def getControls(self): controls.setAttr('progressColor', '#bbbbbb') controls.setAttr('backgroundColor', '#FFFFFF') controls.setAttr('playlist', True) - + return controls - - + + def getContentTop(self): """ Create and configure a content plugin @@ -106,10 +106,10 @@ def getContentTop(self): content.setAttr('backgroundGradient', 'low') content.setAttr('opacity', 0.9) content.addListener(self) - + return content - - + + def getContentBottom(self): """ Create and configure another content plugin @@ -125,12 +125,12 @@ def getContentBottom(self): content.setAttr('backgroundGradient', 'low') content.setAttr('opacity', 0.9) content.addListener(self) - + return content - - + + # Player events - + def onLoadPlayer(self): """ This is a Player Event @@ -140,7 +140,7 @@ def onLoadPlayer(self): # Load a Content-Plugin at runtime into the player content = self.getContentBottom() self.player.loadPlugin(content) - + def onLoadPlugin(self, name): """ This is a Player Event @@ -153,7 +153,7 @@ def onLoadPlugin(self, name): props = {'width': 80, 'bottom': 40, 'left': 40, 'height': 30} content.animate(props) content.setHtml('Click me') - + def onClipAdd(self, clip, index): """ This is a Player Event @@ -161,7 +161,7 @@ def onClipAdd(self, clip, index): """ #log.debug('Clip %s on index %s added' % (clip.url, index)) pass - + def onPlaylistReplace(self, clips): """ This is a Player Event @@ -169,17 +169,17 @@ def onPlaylistReplace(self, clips): """ #log.debug('Playlist is replaced') pass - + def onError(self, args): """ This is a Player Event Fired on an error """ log.debug('Error: %s' % str(args)) - - + + # Plugin events - + def onClickPlugin(self, plugin): """ This is a Plugin Event @@ -199,7 +199,7 @@ def onClickPlugin(self, plugin): #clip.addListener(self) #log.debug('Add Clip') #self.player.addClip(clip, 3) - + def onAnimatePlugin(self, plugin): """ This is a Plugin Event @@ -207,9 +207,9 @@ def onAnimatePlugin(self, plugin): """ #log.debug('Plugin %s animated' % plugin.name) pass - + # Clip events - + def onResume(self, clip): """ This is a Clip Event @@ -219,7 +219,7 @@ def onResume(self, clip): # Get the contentTop plugin, and fade it out plugin = self.player.getPlugin('contentTop') plugin.fadeOut() - + def onPause(self, clip): """ This is a Clip Event @@ -232,7 +232,7 @@ def onPause(self, clip): plugin.setHtml('%s' % clip.url) plugin.append('
More Text') plugin.fadeIn() - + if __name__ == '__main__': app = FlowPlayerExample() diff --git a/examples/misc/flowplayer/server.py b/examples/misc/flowplayer/server.py index 6a7fa709e..ceb63db0c 100644 --- a/examples/misc/flowplayer/server.py +++ b/examples/misc/flowplayer/server.py @@ -11,7 +11,7 @@ import urllib class Server: - + def __init__(self): server_address = ('', 8080) httpd = TestHTTPServer(server_address, TestRequestHandler) @@ -20,17 +20,17 @@ def __init__(self): class TestHTTPServer(ThreadingMixIn, HTTPServer): pass - - + + class TestRequestHandler(BaseHTTPRequestHandler): - + def __init__(self, request, client_address, server): BaseHTTPRequestHandler.__init__(self, request, client_address, server) self.protocol_version = 'HTTP/1.1' - + def do_GET(self): self.handle_data() - + def do_POST(self): self.form = cgi.FieldStorage( fp=self.rfile, @@ -41,7 +41,7 @@ def do_POST(self): keep_blank_values=True, strict_parsing=False) self.handle_data() - + def handle_data(self): if self.path == '/': p = '/html/fp.html' @@ -64,7 +64,7 @@ def handle_data(self): self.end_headers() self.copyfile(f, self.wfile) f.close() - + def translate_path(self, path): path = path.decode('utf-8') path = urlparse.urlparse(path)[2] @@ -78,10 +78,10 @@ def translate_path(self, path): if word in (os.curdir, os.pardir): continue path = os.path.join(path, word) return path - + def copyfile(self, source, outputfile): shutil.copyfileobj(source, outputfile) - + def guess_type(self, path): base, ext = posixpath.splitext(path) if ext in self.extensions_map: @@ -98,7 +98,7 @@ def guess_type(self, path): extensions_map.update({ '': 'application/octet-stream', # Default }) - - + + if __name__ == '__main__': Server() \ No newline at end of file diff --git a/examples/misc/gaedjangononrelpuremvcblog/__main__.py b/examples/misc/gaedjangononrelpuremvcblog/__main__.py index ebf6820b3..707f64f77 100644 --- a/examples/misc/gaedjangononrelpuremvcblog/__main__.py +++ b/examples/misc/gaedjangononrelpuremvcblog/__main__.py @@ -15,7 +15,7 @@ ], downloads=[ dict( - url='http://puremvc.org/pages/downloads/Python/PureMVC_Python.zip', + url='http://puremvc.org/pages/downloads/Python/PureMVC_Python.zip', dst=os.path.join(puremvc, 'PureMVC_Python.zip'), unzip=True, ) diff --git a/examples/misc/gaedjangononrelpuremvcblog/media/controller.py b/examples/misc/gaedjangononrelpuremvcblog/media/controller.py index 859502fa4..03c5a06ca 100644 --- a/examples/misc/gaedjangononrelpuremvcblog/media/controller.py +++ b/examples/misc/gaedjangononrelpuremvcblog/media/controller.py @@ -1,29 +1,29 @@ -""" -By Scott Scites -Copyright(c) 2010 Scott Scites, Some rights reserved. -""" - -from puremvc.patterns.command import SimpleCommand -from model import PostRemoteProxy -from view import HomeMediator -from view import WriteMediator -from view import EditMediator - - -class StartupCommand(SimpleCommand): - def execute(self, note): - self.facade.registerProxy(PostRemoteProxy()) - main_panel = note.getBody() - self.facade.registerMediator(HomeMediator - (main_panel.home_panel)) - self.facade.registerMediator(WriteMediator - (main_panel.write_panel)) - self.facade.registerMediator(EditMediator - (main_panel.edit_panel)) - - -class GetPostsCommand(SimpleCommand): - def execute(self, note): - facade = self.facade - postProxy = facade.retrieveProxy(PostRemoteProxy.NAME) - postProxy.retrieve_posts() +""" +By Scott Scites +Copyright(c) 2010 Scott Scites, Some rights reserved. +""" + +from puremvc.patterns.command import SimpleCommand +from model import PostRemoteProxy +from view import HomeMediator +from view import WriteMediator +from view import EditMediator + + +class StartupCommand(SimpleCommand): + def execute(self, note): + self.facade.registerProxy(PostRemoteProxy()) + main_panel = note.getBody() + self.facade.registerMediator(HomeMediator + (main_panel.home_panel)) + self.facade.registerMediator(WriteMediator + (main_panel.write_panel)) + self.facade.registerMediator(EditMediator + (main_panel.edit_panel)) + + +class GetPostsCommand(SimpleCommand): + def execute(self, note): + facade = self.facade + postProxy = facade.retrieveProxy(PostRemoteProxy.NAME) + postProxy.retrieve_posts() diff --git a/examples/misc/gaedjangononrelpuremvcblog/media/model.py b/examples/misc/gaedjangononrelpuremvcblog/media/model.py index 62b79adf5..214e03c70 100644 --- a/examples/misc/gaedjangononrelpuremvcblog/media/model.py +++ b/examples/misc/gaedjangononrelpuremvcblog/media/model.py @@ -1,100 +1,100 @@ -""" -By Scott Scites -Copyright(c) 2010 Scott Scites, Some rights reserved. -""" - -from pyjamas.JSONService import JSONProxy -from puremvc.patterns.proxy import Proxy -import vo -import Blog - - -class PostRemoteProxy(Proxy): - NAME = "PostRemoteProxy" - - def __init__(self): - super(PostRemoteProxy, self).__init__(PostRemoteProxy.NAME, []) - self.data = [] - self.remote = DataService() - - def get_posts(self): - return self.data - - def get_reversed_posts(self): - return sorted(self.data, key=lambda post: post.post_id, reverse=True) - - def get_post(self, post_id): - for i in range(len(self.data)): - if self.data[i].post_id == post_id: - return self.data[i] - - def add_blog_post(self, post): - self.data.append(post) - - def update_blog_post(self, post): - for i in range(len(self.data)): - if self.data[i].post_id == post.post_id: - self.data[i] = post - - def delete_post(self, post_id): - for i in range(len(self.data)): - if self.data[i].post_id == post_id: - del self.data[i] - self.sendNotification(Blog.AppFacade.POST_DELETED) - return - - def retrieve_posts(self): - id = self.remote.get_posts(self) - if id < 0: - self.sendNotification(Blog.AppFacade.POST_REMOTE_FAILURE) - - """ - Adds a given C{PostVO} to the datastore. - """ - def add_remote_blog_post(self, title, content): - id = self.remote.add_post(title, content, self) - if id < 0: - self.sendNotification(Blog.AppFacade.POST_REMOTE_FAILURE) - - def edit_remote_blog_post(self, key, title, content): - id = self.remote.update_post(key, title, content, self) - if id < 0: - self.sendNotification(Blog.AppFacade.POST_REMOTE_FAILURE) - - """ - Deletes a post from the datastore by its unique key. - """ - def delete_remote_post(self, key): - id = self.remote.delete_post(key, self) - if id < 0: - self.sendNotification(Blog.AppFacade.POST_REMOTE_FAILURE) - - def onRemoteResponse(self, response, request_info): - if request_info.method == 'get_posts': - for post in response: - self.add_blog_post(vo.PostVO - (post[0], post[1], post[2])) - self.sendNotification(Blog.AppFacade.POSTS_RETRIEVED) - elif request_info.method == 'add_post': - blog_post = vo.PostVO(response[0][0], response[0][1], response[0][2]) - self.add_blog_post(blog_post) - self.sendNotification(Blog.AppFacade.POST_ADDED, blog_post) - elif request_info.method == 'update_post': - post = response - for post in response: - self.update_blog_post(vo.PostVO(post[0], post[1], post[2])) - self.sendNotification(Blog.AppFacade.POST_EDITED) - elif request_info.method == 'delete_post': - post_number = response - self.delete_post(post_number) - else: - self.sendNotification(Blog.AppFacade.POST_REMOTE_NONE) - - def onRemoteError(self, code, message, request_info): - self.sendNotification(Blog.AppFacade.POST_REMOTE_FAILURE) - - -class DataService(JSONProxy): - def __init__(self): - JSONProxy.__init__(self, "/services/", ["add_post", - "get_posts", "update_post", "delete_post"]) +""" +By Scott Scites +Copyright(c) 2010 Scott Scites, Some rights reserved. +""" + +from pyjamas.JSONService import JSONProxy +from puremvc.patterns.proxy import Proxy +import vo +import Blog + + +class PostRemoteProxy(Proxy): + NAME = "PostRemoteProxy" + + def __init__(self): + super(PostRemoteProxy, self).__init__(PostRemoteProxy.NAME, []) + self.data = [] + self.remote = DataService() + + def get_posts(self): + return self.data + + def get_reversed_posts(self): + return sorted(self.data, key=lambda post: post.post_id, reverse=True) + + def get_post(self, post_id): + for i in range(len(self.data)): + if self.data[i].post_id == post_id: + return self.data[i] + + def add_blog_post(self, post): + self.data.append(post) + + def update_blog_post(self, post): + for i in range(len(self.data)): + if self.data[i].post_id == post.post_id: + self.data[i] = post + + def delete_post(self, post_id): + for i in range(len(self.data)): + if self.data[i].post_id == post_id: + del self.data[i] + self.sendNotification(Blog.AppFacade.POST_DELETED) + return + + def retrieve_posts(self): + id = self.remote.get_posts(self) + if id < 0: + self.sendNotification(Blog.AppFacade.POST_REMOTE_FAILURE) + + """ + Adds a given C{PostVO} to the datastore. + """ + def add_remote_blog_post(self, title, content): + id = self.remote.add_post(title, content, self) + if id < 0: + self.sendNotification(Blog.AppFacade.POST_REMOTE_FAILURE) + + def edit_remote_blog_post(self, key, title, content): + id = self.remote.update_post(key, title, content, self) + if id < 0: + self.sendNotification(Blog.AppFacade.POST_REMOTE_FAILURE) + + """ + Deletes a post from the datastore by its unique key. + """ + def delete_remote_post(self, key): + id = self.remote.delete_post(key, self) + if id < 0: + self.sendNotification(Blog.AppFacade.POST_REMOTE_FAILURE) + + def onRemoteResponse(self, response, request_info): + if request_info.method == 'get_posts': + for post in response: + self.add_blog_post(vo.PostVO + (post[0], post[1], post[2])) + self.sendNotification(Blog.AppFacade.POSTS_RETRIEVED) + elif request_info.method == 'add_post': + blog_post = vo.PostVO(response[0][0], response[0][1], response[0][2]) + self.add_blog_post(blog_post) + self.sendNotification(Blog.AppFacade.POST_ADDED, blog_post) + elif request_info.method == 'update_post': + post = response + for post in response: + self.update_blog_post(vo.PostVO(post[0], post[1], post[2])) + self.sendNotification(Blog.AppFacade.POST_EDITED) + elif request_info.method == 'delete_post': + post_number = response + self.delete_post(post_number) + else: + self.sendNotification(Blog.AppFacade.POST_REMOTE_NONE) + + def onRemoteError(self, code, message, request_info): + self.sendNotification(Blog.AppFacade.POST_REMOTE_FAILURE) + + +class DataService(JSONProxy): + def __init__(self): + JSONProxy.__init__(self, "/services/", ["add_post", + "get_posts", "update_post", "delete_post"]) diff --git a/examples/misc/gaedjangononrelpuremvcblog/media/view.py b/examples/misc/gaedjangononrelpuremvcblog/media/view.py index 824163743..8531cc7a3 100644 --- a/examples/misc/gaedjangononrelpuremvcblog/media/view.py +++ b/examples/misc/gaedjangononrelpuremvcblog/media/view.py @@ -1,194 +1,194 @@ -""" -By Scott Scites -Copyright(c) 2010 Scott Scites, Some rights reserved. -""" - -from puremvc.patterns.mediator import Mediator -import model -import Blog - - -class HomeMediator(Mediator): - NAME = "HomeMediator" - post_remote_proxy = None - - def __init__(self, viewComponent): - super(HomeMediator, self).__init__(HomeMediator.NAME, viewComponent) - self.viewComponent.mediator = self - self.post_remote_proxy = self.facade.retrieveProxy(model.PostRemoteProxy.NAME) - self.viewComponent.write_button.addClickListener(self.on_write_click) - self.viewComponent.edit_hidden_button.addClickListener(self.on_edit_click) - self.viewComponent.delete_hidden_button.addClickListener(self.on_delete_click) - - def listNotificationInterests(self): - return [Blog.AppFacade.POSTS_RETRIEVED, - Blog.AppFacade.POST_ADDED, - Blog.AppFacade.POST_EDITED, - Blog.AppFacade.POST_DELETED, - Blog.AppFacade.EDIT_CANCELED] - - def handleNotification(self, note): - note_name = note.getName() - if note_name == Blog.AppFacade.POSTS_RETRIEVED: - self.update_posts() - if note_name == Blog.AppFacade.POST_ADDED: - self.clear_update_posts() - if note_name == Blog.AppFacade.POST_EDITED: - self.clear_update_posts() - if note_name == Blog.AppFacade.POST_DELETED: - self.clear_update_posts() - if note_name == Blog.AppFacade.EDIT_CANCELED: - self.clear_hidden_id() - - def clear_update_posts(self): - self.clear_posts() - self.clear_hidden_id() - self.update_posts() - - def clear_posts(self): - self.viewComponent.remove(self.viewComponent.contents) - - def clear_hidden_id(self): - self.viewComponent.edit_hidden_button.setID("") - self.viewComponent.delete_hidden_button.setID("") - - def update_posts(self): - posts = self.post_remote_proxy.get_reversed_posts() - self.viewComponent.update_posts(posts) - - def on_write_click(self): - self.sendNotification(Blog.AppFacade.VIEW_WRITE_POST) - - def is_click_id_set(self, sender_id): - if sender_id == "" or sender_id == None: - return False - return True - - def on_edit_click(self, sender=None): - if self.is_click_id_set(sender.getID()): - self.sendNotification(Blog.AppFacade.VIEW_EDIT_POST, sender.getID()) - - def on_delete_click(self, sender=None): - if self.is_click_id_set(sender.getID()): - key = sender.getID() - post_id = key.replace("delete_", "") - self.post_remote_proxy.delete_remote_post(post_id) - - -class WriteMediator(Mediator): - NAME = "WriteMediator" - post_remote_proxy = None - - def __init__(self, viewComponent): - super(WriteMediator, self).__init__(WriteMediator.NAME, viewComponent) - self.viewComponent.mediator = self - self.post_remote_proxy = self.facade.retrieveProxy(model.PostRemoteProxy.NAME) - self.viewComponent.post_button.addClickListener(self.add_post) - self.viewComponent.cancel_button.addClickListener(self.on_close) - - def listNotificationInterests(self): - return [Blog.AppFacade.VIEW_WRITE_POST] - - def handleNotification(self, note): - note_name = note.getName() - if note_name == Blog.AppFacade.VIEW_WRITE_POST: - self.view_write_post(self) - - def view_write_post(self, event): - self.viewComponent.clear_write_panel() - self.viewComponent.dialog.show() - self.viewComponent.post_title.setFocus(True) - - def on_close(self, event): - self.viewComponent.dialog.hide() - - def validate_add(self): - error_message = "" - title = self.viewComponent.post_title.getText() - if title == "": - self.viewComponent.post_title.setFocus(True) - return ("Title is a required field", title, content) - content = self.viewComponent.post_content.getText() - if content == "": - self.viewComponent.post_content.setFocus(True) - return ("Content is a required field", title, content) - if len(content) > 255: - self.viewComponent.post_content.setFocus(True) - return ("Post body must be less than 256 characters. It is " + str(len(content)), title, content) - return (error_message, title, content) - - def add_post(self, event): - error_message, title, content = self.validate_add() - if len(error_message) > 0: - (self.viewComponent. - error_message_label. - setText(error_message)) - return - title = self.viewComponent.post_title.getText() - content = self.viewComponent.post_content.getText() - self.post_remote_proxy.add_remote_blog_post(title, content) - self.on_close() - - -class EditMediator(Mediator): - NAME = "EditMediator" - edit_remote_proxy = None - - def __init__(self, viewComponent): - super(EditMediator, self).__init__(EditMediator.NAME, viewComponent) - self.viewComponent.mediator = self - self.edit_remote_proxy = self.facade.retrieveProxy(model.PostRemoteProxy.NAME) - self.viewComponent.edit_button.addClickListener(self.edit_post) - self.viewComponent.edit_cancel_button.addClickListener(self.on_edit_close) - - def listNotificationInterests(self): - return [Blog.AppFacade.VIEW_EDIT_POST] - - def handleNotification(self, note): - note_name = note.getName() - note_body = note.getBody() - if note_name == Blog.AppFacade.VIEW_EDIT_POST: - self.view_edit_post(note_body) - - def view_edit_post(self, post_key): - self.viewComponent.clear_edit_panel() - self.viewComponent.edit_dialog.show() - post_id = post_key.replace("edit_", "") - post = self.edit_remote_proxy.get_post(post_id) - self.viewComponent.edit_title.setText(post.title) - self.viewComponent.edit_title.setFocus(True) - self.viewComponent.edit_content.setText(post.content) - self.viewComponent.edit_hidden_key.setValue(post_id) - - def validate_edit(self): - error_message = "" - key = self.viewComponent.edit_hidden_key.getValue() - if key == "": - return ("Cannot update without a post identifier", key, title, content) - title = self.viewComponent.edit_title.getText() - if title == "": - self.viewComponent.edit_title.setFocus(True) - return ("Title is a required field", key, title, content) - content = self.viewComponent.edit_content.getText() - if content == "": - self.viewComponent.edit_content.setFocus(True) - return ("Content is a required field", key, title, content) - if len(content) > 255: - self.viewComponent.edit_content.setFocus(True) - return ("Post body must be less than 255 characters. It is " + str(len(content)), key, title, content) - return (error_message, key, title, content) - - def on_edit_close(self, event): - self.viewComponent.edit_dialog.hide() - self.sendNotification(Blog.AppFacade.EDIT_CANCELED) - - def edit_post(self, event): - error_message, key, title, content = self.validate_edit() - if len(error_message) > 0: - (self. - viewComponent. - error_message_label. - setText(error_message)) - return - self.edit_remote_proxy.edit_remote_blog_post(key, title, content) - self.on_edit_close() +""" +By Scott Scites +Copyright(c) 2010 Scott Scites, Some rights reserved. +""" + +from puremvc.patterns.mediator import Mediator +import model +import Blog + + +class HomeMediator(Mediator): + NAME = "HomeMediator" + post_remote_proxy = None + + def __init__(self, viewComponent): + super(HomeMediator, self).__init__(HomeMediator.NAME, viewComponent) + self.viewComponent.mediator = self + self.post_remote_proxy = self.facade.retrieveProxy(model.PostRemoteProxy.NAME) + self.viewComponent.write_button.addClickListener(self.on_write_click) + self.viewComponent.edit_hidden_button.addClickListener(self.on_edit_click) + self.viewComponent.delete_hidden_button.addClickListener(self.on_delete_click) + + def listNotificationInterests(self): + return [Blog.AppFacade.POSTS_RETRIEVED, + Blog.AppFacade.POST_ADDED, + Blog.AppFacade.POST_EDITED, + Blog.AppFacade.POST_DELETED, + Blog.AppFacade.EDIT_CANCELED] + + def handleNotification(self, note): + note_name = note.getName() + if note_name == Blog.AppFacade.POSTS_RETRIEVED: + self.update_posts() + if note_name == Blog.AppFacade.POST_ADDED: + self.clear_update_posts() + if note_name == Blog.AppFacade.POST_EDITED: + self.clear_update_posts() + if note_name == Blog.AppFacade.POST_DELETED: + self.clear_update_posts() + if note_name == Blog.AppFacade.EDIT_CANCELED: + self.clear_hidden_id() + + def clear_update_posts(self): + self.clear_posts() + self.clear_hidden_id() + self.update_posts() + + def clear_posts(self): + self.viewComponent.remove(self.viewComponent.contents) + + def clear_hidden_id(self): + self.viewComponent.edit_hidden_button.setID("") + self.viewComponent.delete_hidden_button.setID("") + + def update_posts(self): + posts = self.post_remote_proxy.get_reversed_posts() + self.viewComponent.update_posts(posts) + + def on_write_click(self): + self.sendNotification(Blog.AppFacade.VIEW_WRITE_POST) + + def is_click_id_set(self, sender_id): + if sender_id == "" or sender_id == None: + return False + return True + + def on_edit_click(self, sender=None): + if self.is_click_id_set(sender.getID()): + self.sendNotification(Blog.AppFacade.VIEW_EDIT_POST, sender.getID()) + + def on_delete_click(self, sender=None): + if self.is_click_id_set(sender.getID()): + key = sender.getID() + post_id = key.replace("delete_", "") + self.post_remote_proxy.delete_remote_post(post_id) + + +class WriteMediator(Mediator): + NAME = "WriteMediator" + post_remote_proxy = None + + def __init__(self, viewComponent): + super(WriteMediator, self).__init__(WriteMediator.NAME, viewComponent) + self.viewComponent.mediator = self + self.post_remote_proxy = self.facade.retrieveProxy(model.PostRemoteProxy.NAME) + self.viewComponent.post_button.addClickListener(self.add_post) + self.viewComponent.cancel_button.addClickListener(self.on_close) + + def listNotificationInterests(self): + return [Blog.AppFacade.VIEW_WRITE_POST] + + def handleNotification(self, note): + note_name = note.getName() + if note_name == Blog.AppFacade.VIEW_WRITE_POST: + self.view_write_post(self) + + def view_write_post(self, event): + self.viewComponent.clear_write_panel() + self.viewComponent.dialog.show() + self.viewComponent.post_title.setFocus(True) + + def on_close(self, event): + self.viewComponent.dialog.hide() + + def validate_add(self): + error_message = "" + title = self.viewComponent.post_title.getText() + if title == "": + self.viewComponent.post_title.setFocus(True) + return ("Title is a required field", title, content) + content = self.viewComponent.post_content.getText() + if content == "": + self.viewComponent.post_content.setFocus(True) + return ("Content is a required field", title, content) + if len(content) > 255: + self.viewComponent.post_content.setFocus(True) + return ("Post body must be less than 256 characters. It is " + str(len(content)), title, content) + return (error_message, title, content) + + def add_post(self, event): + error_message, title, content = self.validate_add() + if len(error_message) > 0: + (self.viewComponent. + error_message_label. + setText(error_message)) + return + title = self.viewComponent.post_title.getText() + content = self.viewComponent.post_content.getText() + self.post_remote_proxy.add_remote_blog_post(title, content) + self.on_close() + + +class EditMediator(Mediator): + NAME = "EditMediator" + edit_remote_proxy = None + + def __init__(self, viewComponent): + super(EditMediator, self).__init__(EditMediator.NAME, viewComponent) + self.viewComponent.mediator = self + self.edit_remote_proxy = self.facade.retrieveProxy(model.PostRemoteProxy.NAME) + self.viewComponent.edit_button.addClickListener(self.edit_post) + self.viewComponent.edit_cancel_button.addClickListener(self.on_edit_close) + + def listNotificationInterests(self): + return [Blog.AppFacade.VIEW_EDIT_POST] + + def handleNotification(self, note): + note_name = note.getName() + note_body = note.getBody() + if note_name == Blog.AppFacade.VIEW_EDIT_POST: + self.view_edit_post(note_body) + + def view_edit_post(self, post_key): + self.viewComponent.clear_edit_panel() + self.viewComponent.edit_dialog.show() + post_id = post_key.replace("edit_", "") + post = self.edit_remote_proxy.get_post(post_id) + self.viewComponent.edit_title.setText(post.title) + self.viewComponent.edit_title.setFocus(True) + self.viewComponent.edit_content.setText(post.content) + self.viewComponent.edit_hidden_key.setValue(post_id) + + def validate_edit(self): + error_message = "" + key = self.viewComponent.edit_hidden_key.getValue() + if key == "": + return ("Cannot update without a post identifier", key, title, content) + title = self.viewComponent.edit_title.getText() + if title == "": + self.viewComponent.edit_title.setFocus(True) + return ("Title is a required field", key, title, content) + content = self.viewComponent.edit_content.getText() + if content == "": + self.viewComponent.edit_content.setFocus(True) + return ("Content is a required field", key, title, content) + if len(content) > 255: + self.viewComponent.edit_content.setFocus(True) + return ("Post body must be less than 255 characters. It is " + str(len(content)), key, title, content) + return (error_message, key, title, content) + + def on_edit_close(self, event): + self.viewComponent.edit_dialog.hide() + self.sendNotification(Blog.AppFacade.EDIT_CANCELED) + + def edit_post(self, event): + error_message, key, title, content = self.validate_edit() + if len(error_message) > 0: + (self. + viewComponent. + error_message_label. + setText(error_message)) + return + self.edit_remote_proxy.edit_remote_blog_post(key, title, content) + self.on_edit_close() diff --git a/examples/misc/gaedjangononrelpuremvcblog/media/vo.py b/examples/misc/gaedjangononrelpuremvcblog/media/vo.py index 810828765..7e9a982ee 100644 --- a/examples/misc/gaedjangononrelpuremvcblog/media/vo.py +++ b/examples/misc/gaedjangononrelpuremvcblog/media/vo.py @@ -1,28 +1,28 @@ -""" -By Scott Scites -Copyright(c) 2010 Scott Scites, Some rights reserved. -""" - - -class PostVO(object): - post_id = None - title = None - content = None - - def __init__(self, post_id=None, title=None, - content=None): - if post_id: - self.post_id = post_id - if title: - self.title = title - if content: - self.content = content - - def is_empty(self): - if self.post_id: - return False - if self.title: - return False - if self.content: - return False - return True +""" +By Scott Scites +Copyright(c) 2010 Scott Scites, Some rights reserved. +""" + + +class PostVO(object): + post_id = None + title = None + content = None + + def __init__(self, post_id=None, title=None, + content=None): + if post_id: + self.post_id = post_id + if title: + self.title = title + if content: + self.content = content + + def is_empty(self): + if self.post_id: + return False + if self.title: + return False + if self.content: + return False + return True diff --git a/examples/misc/gaedjangononrelpuremvcblog/post/jsonrpc.py b/examples/misc/gaedjangononrelpuremvcblog/post/jsonrpc.py index b5fa5d929..337bdbe79 100644 --- a/examples/misc/gaedjangononrelpuremvcblog/post/jsonrpc.py +++ b/examples/misc/gaedjangononrelpuremvcblog/post/jsonrpc.py @@ -31,10 +31,10 @@ def error(id, code, message): class JSONRPCService: def __init__(self, method_map=None): self.method_map = method_map or {} - + def add_method(self, name, method): self.method_map[name] = method - + def __call__(self, request, extra=None): # We do not yet support GET requests, something pyjamas does # not use anyways. @@ -58,7 +58,7 @@ def __call__(self, request, extra=None): def jsonremote(service): """Make JSONRPCService a decorator so that you can write : - + from jsonrpc import JSONRPCService chatservice = JSONRPCService() @@ -96,7 +96,7 @@ def remotify(func): # (r'^formsservice/$', 'djangoapp.views.processor'), -from django import forms +from django import forms def builderrors(form): d = {} diff --git a/examples/misc/gaedjangononrelpuremvcblog/post/views.py b/examples/misc/gaedjangononrelpuremvcblog/post/views.py index ffa02a090..191b9b27e 100644 --- a/examples/misc/gaedjangononrelpuremvcblog/post/views.py +++ b/examples/misc/gaedjangononrelpuremvcblog/post/views.py @@ -21,7 +21,7 @@ def update_post(request, key, title, content): post = Post.objects.get(id=key) post = map_remote_post_to_local_post(title, content, post) post.save() - return get_post(request, post.pk) + return get_post(request, post.pk) @jsonremote(service) def add_post(request, title, content): diff --git a/examples/misc/scoping/Foo.py b/examples/misc/scoping/Foo.py index e2c88bc3b..da5d4769f 100644 --- a/examples/misc/scoping/Foo.py +++ b/examples/misc/scoping/Foo.py @@ -8,9 +8,9 @@ def b(): class Foo: def __init__(self): Window.alert("Next you should see 'in a', 'in b'") - x = [a, b] + x = [a, b] for f in x: - f() + f() class Bar: @@ -20,9 +20,9 @@ def b(): Window.alert( "in Bar b" ) Window.alert("Next you should see 'in Bar a', 'in Bar b'") - x = [a, b] + x = [a, b] for f in x: - f() + f() def __init__(self): @@ -32,6 +32,6 @@ def b(): Window.alert( "in bar b" ) Window.alert("you should now see 'in bar a', 'in bar b'") - x = [a, b] + x = [a, b] for f in x: - f() + f() diff --git a/examples/misc/simplewiki/Wiki.py b/examples/misc/simplewiki/Wiki.py index 697283443..721d8c95b 100644 --- a/examples/misc/simplewiki/Wiki.py +++ b/examples/misc/simplewiki/Wiki.py @@ -52,7 +52,7 @@ def onChange(self, sender): self.t.getText(), self) - def onRemoteResponse(self, response, request_info): + def onRemoteResponse(self, response, request_info): if request_info.method == 'find_one': self.h.setHTML(response['content']) self.t.setText(response['content']) @@ -61,7 +61,7 @@ def onRemoteError(self, code, message, request_info): log.debug('remote error! ' + str(message)) log.debug('remote error! ' + str(request_info)) - def onKeyUp(self, sender, keycode, modifiers): + def onKeyUp(self, sender, keycode, modifiers): if sender == self.t: self.h.setHTML(self.t.getText()) diff --git a/examples/misc/simplewiki/markdown.py b/examples/misc/simplewiki/markdown.py index e38951c0c..e2c0d2f16 100644 --- a/examples/misc/simplewiki/markdown.py +++ b/examples/misc/simplewiki/markdown.py @@ -23,7 +23,7 @@ def urlmap(txt): txt = esc(beg) + "" % url txt += "%s" % esc(url) + urlmap(end) return txt - + def ts(txt): l = txt.split('\n') r = [] @@ -51,7 +51,7 @@ def makeHTML(text): txt += line txt += "\n" continue - + line = line.strip() ul_line = False ul_line2 = False diff --git a/examples/misc/simplewiki/server.py b/examples/misc/simplewiki/server.py index 3287f0d1d..0091788c8 100644 --- a/examples/misc/simplewiki/server.py +++ b/examples/misc/simplewiki/server.py @@ -14,7 +14,7 @@ def find_one(self, name): f.close() return {'name': name, 'content': text} except: - return {'name':name, + return {'name':name, 'content':'Nothing here... yet'} def insert(self, name, content): diff --git a/examples/misc/swfupload/server.py b/examples/misc/swfupload/server.py index 9f9b20d3f..397f9642e 100644 --- a/examples/misc/swfupload/server.py +++ b/examples/misc/swfupload/server.py @@ -11,7 +11,7 @@ import urllib class Server: - + def __init__(self): server_address = ('', 8080) httpd = TestHTTPServer(server_address, TestRequestHandler) @@ -20,17 +20,17 @@ def __init__(self): class TestHTTPServer(ThreadingMixIn, HTTPServer): pass - - + + class TestRequestHandler(BaseHTTPRequestHandler): - + def __init__(self, request, client_address, server): BaseHTTPRequestHandler.__init__(self, request, client_address, server) self.protocol_version = 'HTTP/1.1' - + def do_GET(self): self.handle_data() - + def do_POST(self): self.form = cgi.FieldStorage( fp=self.rfile, @@ -41,7 +41,7 @@ def do_POST(self): keep_blank_values=True, strict_parsing=False) self.handle_data() - + def handle_data(self): if self.path == '/': p = '/html/swfu.html' @@ -67,7 +67,7 @@ def handle_data(self): self.end_headers() self.copyfile(f, self.wfile) f.close() - + def handleUpload(self): self.send_response(200) self.end_headers() @@ -85,7 +85,7 @@ def fbuffer(f, chunk_size=10000): f.close() self.wfile.write('Upload done') return - + def translate_path(self, path): path = path.decode('utf-8') path = urlparse.urlparse(path)[2] @@ -99,10 +99,10 @@ def translate_path(self, path): if word in (os.curdir, os.pardir): continue path = os.path.join(path, word) return path - + def copyfile(self, source, outputfile): shutil.copyfileobj(source, outputfile) - + def guess_type(self, path): base, ext = posixpath.splitext(path) if ext in self.extensions_map: @@ -120,7 +120,6 @@ def guess_type(self, path): '': 'application/octet-stream', # Default }) - + if __name__ == '__main__': Server() - \ No newline at end of file diff --git a/examples/misc/swfupload/swfu.py b/examples/misc/swfupload/swfu.py index 07edef25d..add6258b9 100644 --- a/examples/misc/swfupload/swfu.py +++ b/examples/misc/swfupload/swfu.py @@ -9,105 +9,104 @@ class SWFUploadExample(SWFUploadInterface): - + def onModuleLoad(self): self.panel = VerticalPanel() self.panel.setSpacing(10) RootPanel().add(self.panel) - + self.swfUpload = self.getSWFUpload() self.panel.add(self.swfUpload) - + self.fileids = [] self.queue = VerticalPanel() self.panel.add(self.queue) - + startButton = Button('Start Upload') startButton.addClickListener(getattr(self, 'onStartUpload')) self.panel.add(startButton) - + self.progress = Label() self.panel.add(self.progress) - + def getSWFUpload(self): swfUpload = SWFUpload() swfUpload.setSettings(self.getSettings()) swfUpload.setID('SWFUploadPanel') return swfUpload - + def showQueue(self): self.queue.clear() for fileid in self.fileids: file = self.swfUpload.getFile(fileid) label = Label('%s (%s Bytes)' % (file.name, file.size)) self.queue.add(label) - + def getSettings(self): settings = Settings() settings.setURL('upload.html') - + settings.setButtonHTML('add Files') settings.setButtonCSS('.uploadButton { font-size: 12; font-weight: bold; }') settings.setButtonWidth(60) settings.setButtonHeight(25) settings.setButtonTopPadding(10) settings.setButtonLeftPadding(5) - + settings.setEventListener(self) settings.setFlashURL('swf/swfupload.swf') - + return settings - + def onStartUpload(self): #log.debug('Starting Upload') self.swfUpload.startUpload() - + """ SWFUpload Events """ - + def swfUploadLoaded(self): #log.debug('swfUploadLoaded') pass - + def uploadProgress(self, file, bytesLoaded, totalBytes): self.progress.setText('%s - %s of %s uploaded' % (file.name, bytesLoaded, totalBytes)) - + def uploadError(self, file, errorCode, message): log.debug('uploadError: %s, %s' % (errorCode, message)) - + def uploadSuccess(self, file, receivedResponse, serverData): self.fileids.remove(file.id) self.showQueue() - + def uploadComplete(self, file): #log.debug('uploadComplete: %s' % file.name) if len(self.fileids) > 0: self.swfUpload.startUpload() else: self.progress.setText('All files uploaded') - + def fileDialogStart(self): #log.debug('fileDialogStart') pass - + def fileQueued(self, file): #log.debug('fileQueued: %s' % file.name) self.fileids.append(file.id) - + def fileQueueError(self, file, errorCode, message): log.debug('fileQueueError: %s, %s' % (errorCode, message)) - + def fileDialogComplete(self, sel, qu, tqu): #log.debug('fileDialogComplete: %s, %s, %s' % (sel, qu, tqu)) self.showQueue() - + def uploadStart(self, file): #log.debug('uploadStart') # Do something before the upload starts, and return True to start the upload return True - + if __name__ == '__main__': app = SWFUploadExample() app.onModuleLoad() - \ No newline at end of file diff --git a/examples/navigate/Navigate.py b/examples/navigate/Navigate.py index 3a4bf8b02..3c6adb88b 100644 --- a/examples/navigate/Navigate.py +++ b/examples/navigate/Navigate.py @@ -78,7 +78,7 @@ def onChange(self, sender): def set(self, parentBuoy): self.parent_buoy = parentBuoy params = parentBuoy.plan() - if params: + if params: for n, tab in enumerate(self.tabs): if tab['name'] in params['hovertype']: self.selectTab(n) @@ -142,8 +142,8 @@ def onTabSelected(self, sender, tabIndex): buoy = self.parent_buoy.new(page_name, {page_name : None}) - - + + if tabIndex == 0: buoy.navigate() self.tabs[tabIndex]['tab'].set(buoy) diff --git a/examples/navigate/buoy.py b/examples/navigate/buoy.py index 4c60cb4d1..feb01b23e 100644 --- a/examples/navigate/buoy.py +++ b/examples/navigate/buoy.py @@ -5,7 +5,7 @@ @summary: Manager for handling a web browser's History, & bread crumbs within a Pyjamas application. - Catches the onHistoryChanged() notification of Pyjamas and converts it into a series of objects + Catches the onHistoryChanged() notification of Pyjamas and converts it into a series of objects An app needs to be structured such that any state a user can bookmark can be reached programmatically. Optionally, if <title> and/or breadcrumb are employed @@ -79,7 +79,7 @@ def new(self, title, *args, **kwargs): def checkpoint(self): ''' Checks Buoy for a flare - If not found drops Buoy to mark end state + If not found drops Buoy to mark end state @return: any parameters of flare or {} @rtype: dict @@ -172,7 +172,7 @@ def set_parameters(self, params): params are used to create tokens (/about/history=all) & to drive apps @type params: dict - @param params: {'name' : value} set value to None for valueless parameters + @param params: {'name' : value} set value to None for valueless parameters ''' self.params = params @@ -188,7 +188,7 @@ def add_parameters(self, params): def _get_titles(self): ''' a list of buoy title strings. - used to generate list for setting of <title> content + used to generate list for setting of <title> content @return: list of titles @rtype: list @@ -299,11 +299,11 @@ def deconstruct_token(token): method placed in Buoy rather than BuoyService as it is the mirror of construct_token() - override for an alternative format + override for an alternative format @type token: string @param token: a History token - @return: list of dict parameters + @return: list of dict parameters @rtype: list ''' events = [] @@ -414,7 +414,7 @@ def __init__(self, title, crumb=None): ''' create one BuoyService per application - @param title: Application title + @param title: Application title @type title: string @param crumb: First bread crumb string. Defaults to title @type crumb: string @@ -464,7 +464,7 @@ def set_breadcrumbs_listener(self, listener): installs a sole listener to enable App to update a bread crumb trail @param listener: class instance supporting onBreadcrumbsChanged() method - @type listener: class instance + @type listener: class instance ''' self.breadcrumbs_listener = listener @@ -532,7 +532,7 @@ def onHistoryChanged(self, token): def new_item(self, token): ''' - updates the current URL's hash token. + updates the current URL's hash token. disables the calling of BuoyService's onHistoryChanged() when a Buoy adds a new item @param token: hash token @@ -542,7 +542,7 @@ def new_item(self, token): which calls BuoyService.new_item(). The subsequent call to History.newItem() will call BuoyService.onHistoryChanged() but as the app is already in the correct state there is such requirement. So we smoother it by disabling BuoyService's history listener - until after the new item is added. + until after the new item is added. ''' self._set_history_listener(False) History.newItem(token) @@ -551,7 +551,7 @@ def new_item(self, token): def _build_flares(self, service, token): ''' using ServiceBuoy build a route & events based on a token - + @param service: app's ServiceBuoy instance @type service: serviceBuoy @param token: hash token @@ -573,7 +573,7 @@ def _build_flares(self, service, token): def _set_history_listener(self, on, on_period=251): ''' pyjamas/library/pyjamas/History.py is checking every 250ms if URL has changed - + By default, BuoyService checks every 250+1ms before turning its listener back on. An initial call in BuoyService() set-up needs to set on_period to 1 for immediate listening @@ -590,7 +590,7 @@ def _set_history_listener(self, on, on_period=251): def onTimer(self, id): ''' - turn history listener on once all 'off' periods have completed + turn history listener on once all 'off' periods have completed ''' self.timer_count += 1 if self.timer_count == 1: diff --git a/examples/picasaweb/Photos.py b/examples/picasaweb/Photos.py index a32e326d5..aeeac8ec2 100644 --- a/examples/picasaweb/Photos.py +++ b/examples/picasaweb/Photos.py @@ -1,9 +1,9 @@ # Picasaweb and other gdata services use RESTful methods which is great # for them but presents a problem as far as getting the JSON data without # using the regular pyjamas JSONRPC classes we know and love. Easy if you -# have a backend that can do the get but not so easy to do everything -# client-side since we have to get around Single Origin Policy by dynamically -# adding script tags to the DOM. Check out public/PicasaWeb.html since this +# have a backend that can do the get but not so easy to do everything +# client-side since we have to get around Single Origin Policy by dynamically +# adding script tags to the DOM. Check out public/PicasaWeb.html since this # necessitates a static script tag and a var too. # At this point it works but I'm sure some DOM genius can find some # room for improvement... jkh http://jameskhedley.com @@ -11,9 +11,9 @@ from pyjamas.ui.TextBox import TextBox from pyjamas.ui.Label import Label from pyjamas.ui.Button import Button -from pyjamas.ui.VerticalPanel import VerticalPanel -from pyjamas.ui.HorizontalPanel import HorizontalPanel -from pyjamas.ui.DisclosurePanel import DisclosurePanel +from pyjamas.ui.VerticalPanel import VerticalPanel +from pyjamas.ui.HorizontalPanel import HorizontalPanel +from pyjamas.ui.DisclosurePanel import DisclosurePanel from pyjamas.ui.Grid import Grid from pyjamas.ui.Composite import Composite from pyjamas.Timer import Timer @@ -31,30 +31,30 @@ def __init__(self): self.grid.addTableListener(self) self.drill = 0 self.pos = 0 - self.up = Button("Up", self) - self.next = Button("Next", self) - self.prev = Button("Prev", self) + self.up = Button("Up", self) + self.next = Button("Next", self) + self.prev = Button("Prev", self) self.timer = Timer(notify=self) self.userid = "jameskhedley" self.album_url = "http://picasaweb.google.com/data/feed/base/user/" + self.userid + "?alt=json-in-script&kind=album&hl=en_US&callback=restCb" self.doRESTQuery(self.album_url, self.timer) self.vp = VerticalPanel() - self.disclosure = DisclosurePanel("Click for boring technical details.") + self.disclosure = DisclosurePanel("Click for boring technical details.") self.disclosure.add(HTML('''<p>OK so you want to write client JS to do a RESTful HTTP query from picasa right? Well you can't because of the Same Origin Policy. Basically this means that because the domain of the query and the domain of the hosted site are different, then that could well be a cross-site scripting (XSS) attack. So, the workaround is to - do the call from a script tag so the JSON we get back is part of the document. + do the call from a script tag so the JSON we get back is part of the document. But since we don't know what URL to hit yet, once we find out then we have to inject a new script tag dynamically which the browser will run as soon as we append it. To be honest I'm not 100% why Google use RESTful services and not JSON-RPC or somesuch, which would be easier. Well, easier for me.''')) - + self.IDPanel = HorizontalPanel() self.IDPanel.add(Label("Enter google account:")) self.IDButton = Button("Go", self) - + self.IDBox = TextBox() self.IDBox.setText(self.userid) self.IDPanel.add(self.IDBox) @@ -67,9 +67,9 @@ def __init__(self): def doRESTQuery(self, url, timer): """this is a totally different from an RPC call in that we have to - dynamically add script tags to the DOM when we want to query the - REST API. These rely on callbacks in the DOM so we can either add - them dynamically or pre-define them in public/Main.html. + dynamically add script tags to the DOM when we want to query the + REST API. These rely on callbacks in the DOM so we can either add + them dynamically or pre-define them in public/Main.html. Once we've done that have to wait for the response. Which means we need to provide a listener for the timer""" @@ -81,7 +81,7 @@ def doRESTQuery(self, url, timer): def onCellClicked(self, sender, row, col): if self.drill==0: - self.drill += 1 + self.drill += 1 self.vp.clear() self.grid.clear() self.vp.add(self.up) @@ -140,7 +140,7 @@ def onClick(self, sender): self.vp.add(self.disclosure) self.vp.add(self.grid) self.fillGrid(self.albums, "albums") - + def onTimer(self, timer): fd = doc().getElementById("__pygwt_hiddenData") receiver = fd.innerHTML @@ -178,7 +178,7 @@ def parsePhotos(self, items): for ph in photo_list: aphoto = {} aphoto['thumb'] = HTML('<img src="' + ph[u"media$group"][u"media$thumbnail"][1][u"url"] + '"/>') - aphoto['full'] = ph[u"media$group"][u"media$content"][0][u"url"] + aphoto['full'] = ph[u"media$group"][u"media$content"][0][u"url"] self.photos.append(aphoto) def parseAlbums(self, items): diff --git a/examples/picasaweb/PicasaWeb.py b/examples/picasaweb/PicasaWeb.py index 3a7c78936..e7fa8c2a7 100644 --- a/examples/picasaweb/PicasaWeb.py +++ b/examples/picasaweb/PicasaWeb.py @@ -23,9 +23,9 @@ class PicasaWeb: def onModuleLoad(self): - self.photos=Photos() + self.photos=Photos() RootPanel().add(self.photos) - + if __name__ == '__main__': # for pyjd, set up a web server and load the HTML from there: diff --git a/examples/raphael/events.py b/examples/raphael/events.py index 210d8aa2c..d1f200c87 100644 --- a/examples/raphael/events.py +++ b/examples/raphael/events.py @@ -9,25 +9,25 @@ from pyjamas.ui import HasAlignment from pyjamas import DOM -class Events(VerticalPanel): +class Events(VerticalPanel): def __init__(self,width=600,height=300): - VerticalPanel.__init__(self) + VerticalPanel.__init__(self) self.elements=[] self.desc=[] - - self.canvas = Raphael(width, height) + + self.canvas = Raphael(width, height) self.canvas.addListener('mouseup',self.onCanvasMouseup) self.canvas.addListener('mousemove',self.onCanvasMousemove) self.canvas.addListener('dblclick',self.onCanvasDblClick) self.canvas.addListener('contextmenu',self.onCanvasContextmenu) self.canvas.addListener('mousedown',self.onCanvasMousedown) - + self.add(self.canvas) self.status=Label('Execute any events on the canvas!') self.add(self.status) - + def set_status(self,status): - self.status.setText(status) + self.status.setText(status) def draw(self): @@ -38,13 +38,13 @@ def draw(self): circle1.addListener('mousemove',self.onElementMousemove) circle1.addListener('dblclick',self.onElementDblClick) circle1.addListener('contextmenu',self.onElementContextmenu) - circle1.addListener('mousedown',self.onElementMousedown) + circle1.addListener('mousedown',self.onElementMousedown) self.elements.append(circle1) self.desc.append('Circle 1') - + circle2=self.canvas.circle(100,100,25) circle2.setAttr('fill','#000') - circle2.setAttrs({'cursor':'move','opacity':0.6}) + circle2.setAttrs({'cursor':'move','opacity':0.6}) circle2.addListener('mouseup',self.onElementMouseup) circle2.addListener('mousemove',self.onElementMousemove) circle2.addListener('dblclick',self.onElementDblClick) @@ -62,34 +62,34 @@ def draw(self): rect1.addListener('mousedown',self.onElementMousedown) self.elements.append(rect1) self.desc.append('Rectangle 1') - + rect2=self.canvas.rect(200,150,30,30) rect2.setAttr('fill','#000') rect2.addListener('mouseup',self.onElementMouseup) rect2.addListener('mousemove',self.onElementMousemove) rect2.addListener('dblclick',self.onElementDblClick) rect2.addListener('contextmenu',self.onElementContextmenu) - rect2.addListener('mousedown',self.onElementMousedown) + rect2.addListener('mousedown',self.onElementMousedown) self.elements.append(rect2) self.desc.append('Rectangle 2') - + connection=self.canvas.connection(rect1,rect2) connection.addListener('mouseup',self.onElementMouseup) connection.addListener('mousemove',self.onElementMousemove) connection.addListener('dblclick',self.onElementDblClick) connection.addListener('contextmenu',self.onElementContextmenu) - connection.addListener('mousedown',self.onElementMousedown) + connection.addListener('mousedown',self.onElementMousedown) self.elements.append(connection) - self.desc.append('Connection') - + self.desc.append('Connection') + ellipse=self.canvas.ellipse(200,200,25,40) - text=self.canvas.text(200,200,'ABC') + text=self.canvas.text(200,200,'ABC') set=self.canvas.set() set.add(ellipse) - set.add(text) + set.add(text) set.addListener('mousemove',self.onElementMousemove) self.elements.append(set) - self.desc.append('Set') + self.desc.append('Set') def onCanvasMousedown(self,sender,event): x = DOM.eventGetClientX(event) - DOM.getAbsoluteLeft(self.canvas.getElement()) @@ -100,7 +100,7 @@ def onCanvasMouseup(self,obj,event): x = DOM.eventGetClientX(event) - DOM.getAbsoluteLeft(self.canvas.getElement()) y = DOM.eventGetClientY(event) - DOM.getAbsoluteTop(self.canvas.getElement()) self.set_status('Mousemove on Canvas at '+str(x)+', '+str(y)) - + def onCanvasMousemove(self,sender,event): x = DOM.eventGetClientX(event) - DOM.getAbsoluteLeft(self.canvas.getElement()) y = DOM.eventGetClientY(event) - DOM.getAbsoluteTop(self.canvas.getElement()) @@ -110,7 +110,7 @@ def onCanvasDblClick(self,sender,event): x = DOM.eventGetClientX(event) - DOM.getAbsoluteLeft(self.canvas.getElement()) y = DOM.eventGetClientY(event) - DOM.getAbsoluteTop(self.canvas.getElement()) self.set_status('Doubleclick on Canvas at '+str(x)+', '+str(y)) - + def onCanvasContextmenu(self, sender,event): x = DOM.eventGetClientX(event) - DOM.getAbsoluteLeft(self.canvas.getElement()) y = DOM.eventGetClientY(event) - DOM.getAbsoluteTop(self.canvas.getElement()) @@ -123,14 +123,14 @@ def onElementMousedown(self,sender,event): s = self.desc[self.elements.index(sender)] self.set_status('Mousedown on Element '+s+' at '+str(x)+', '+str(y)) DOM.eventCancelBubble(event,True) - + def onElementMouseup(self,sender,event): x = DOM.eventGetClientX(event) - DOM.getAbsoluteLeft(self.canvas.getElement()) y = DOM.eventGetClientY(event) - DOM.getAbsoluteTop(self.canvas.getElement()) s = self.desc[self.elements.index(sender)] self.set_status('Mouseup on Element '+s+' at '+str(x)+', '+str(y)) DOM.eventCancelBubble(event,True) - + def onElementMousemove(self,sender,event): x = DOM.eventGetClientX(event) - DOM.getAbsoluteLeft(self.canvas.getElement()) y = DOM.eventGetClientY(event) - DOM.getAbsoluteTop(self.canvas.getElement()) @@ -144,7 +144,7 @@ def onElementDblClick(self,sender,event): s = self.desc[self.elements.index(sender)] self.set_status('Doubleclick on Element '+s+' at '+str(x)+', '+str(y)) DOM.eventCancelBubble(event,True) - + def onElementContextmenu(self, sender,event): x = DOM.eventGetClientX(event) - DOM.getAbsoluteLeft(self.canvas.getElement()) y = DOM.eventGetClientY(event) - DOM.getAbsoluteTop(self.canvas.getElement()) @@ -152,8 +152,8 @@ def onElementContextmenu(self, sender,event): self.set_status('Contextmenue on Element '+s+' at '+str(x)+', '+str(y)) DOM.eventCancelBubble(event,True) DOM.eventPreventDefault(event) - -if __name__ == "__main__": + +if __name__ == "__main__": pyjd.setup("public/events.html") events=Events() RootPanel().add(events) diff --git a/examples/raphael/graffle.py b/examples/raphael/graffle.py index 249347adb..bfd1f9098 100644 --- a/examples/raphael/graffle.py +++ b/examples/raphael/graffle.py @@ -11,20 +11,20 @@ from pyjamas import DOM -class Graffle(SimplePanel): +class Graffle(SimplePanel): def __init__(self,width=600,height=300): SimplePanel.__init__(self) - self.canvas = Raphael(width,height) + self.canvas = Raphael(width,height) self.add(self.canvas) def draw(self): self.circle1=self.canvas.circle(50,50,25) self.circle1.setAttr('fill','#000') self.circle1.setAttrs({'cursor':'move','opacity':0.6}) self.circle1.drag(self._move_circle,start,up) - + self.circle2=self.canvas.circle(150,100,25) self.circle2.setAttr('fill','#000') - self.circle2.setAttrs({'cursor':'move','opacity':0.6}) + self.circle2.setAttrs({'cursor':'move','opacity':0.6}) self.circle2.drag(self._move_circle,start,up) self.rect1=self.canvas.rect(200,100,30,30) @@ -34,22 +34,22 @@ def draw(self): self.rect2=self.canvas.rect(200,150,30,30) self.rect2.setAttr('fill','#000') self.rect2.drag(self._move_rect,start,up) - - def connect(self): + + def connect(self): line={'stroke':'#fff','stroke-width':3} - bg={'stroke': '#000', 'stroke-width':5} - self.connection_rect=self.canvas.connection(self.rect1,self.rect2,line=line,bg=bg) + bg={'stroke': '#000', 'stroke-width':5} + self.connection_rect=self.canvas.connection(self.rect1,self.rect2,line=line,bg=bg) line={'stroke':'#fff','stroke-width':3} - bg={'stroke': '#000', 'stroke-width':5} - self.connection_circle=self.canvas.connection(self.circle1,self.circle2,line=line,bg=bg,cp1=DOCK_CONNECTION.EAST,cp2=DOCK_CONNECTION.WEST) - + bg={'stroke': '#000', 'stroke-width':5} + self.connection_circle=self.canvas.connection(self.circle1,self.circle2,line=line,bg=bg,cp1=DOCK_CONNECTION.EAST,cp2=DOCK_CONNECTION.WEST) + def _move_rect(self,obj,dx,dy,x,y): obj.translate(dx-obj.dx,dy-obj.dy) obj.dx=dx obj.dy=dy self.connection_rect.draw() - + def _move_circle(self,obj,dx,dy,x,y): obj.translate(dx-obj.dx,dy-obj.dy) obj.dx=dx @@ -57,15 +57,15 @@ def _move_circle(self,obj,dx,dy,x,y): self.connection_circle.draw() - + def start(obj,x,y): obj.dx=0 obj.dy=0 - + def up(obj): pass -if __name__ == "__main__": +if __name__ == "__main__": pyjd.setup("public/graffle.html") graffle=Graffle() RootPanel().add(graffle) diff --git a/examples/raphael/raphael_showcase.py b/examples/raphael/raphael_showcase.py index f2774a313..aa6f58864 100644 --- a/examples/raphael/raphael_showcase.py +++ b/examples/raphael/raphael_showcase.py @@ -21,23 +21,23 @@ class TabContainer(DockPanel): def __init__(self): - DockPanel.__init__(self, + DockPanel.__init__(self, #BorderWidth=1,Padding=8, HorizontalAlignment=HasAlignment.ALIGN_CENTER, VerticalAlignment=HasAlignment.ALIGN_MIDDLE) - + class TabRaphaelContainer(TabContainer): def __init__(self): TabContainer.__init__(self) self.status=Label() self.add(self.status,DockPanel.SOUTH) - + def set_raphael(self,raphael): self.raphael=raphael self.add(self.raphael,DockPanel.CENTER) #panel.setCellHeight(center, "200px") - #panel.setCellWidth(center, "400px") - + #panel.setCellWidth(center, "400px") + def set_headline(self,headline): if hasattr(self,'html'): self.html.setHTML(headline) @@ -45,18 +45,18 @@ def set_headline(self,headline): else: self.html=HTML(headline) self.add(self.html,DockPanel.NORTH) - + def set_status(self,status): self.status.setText(status) class ShowCaseApp(object): - + def onModuleLoad(self): self.tabs = TabPanel() tab_overview=TabContainer() self.tabs.add(tab_overview, 'Overview') - + self.tab_events=TabRaphaelContainer() self.tab_events.set_headline('Events Example') self.tab_events.set_raphael(events.Events(width=600,height=300)) @@ -72,25 +72,25 @@ def onModuleLoad(self): self.tab_spinner.set_headline('This Raphael Spinner Example') self.tab_spinner.set_raphael(spinner.Spinner(width=600,height=300)) self.tabs.add(self.tab_spinner, 'Spinner') - + self.tabs.selectTab(0) self.tabs.setWidth("100%") self.tabs.setHeight("100%") RootPanel().add(self.tabs) - + def draw(self): self.tab_spinner.raphael.draw() self.tab_graffle.raphael.draw() #self.tab_events.raphael.draw() - -if __name__ == "__main__": + +if __name__ == "__main__": pyjd.setup("public/raphael_showcase.html") app=ShowCaseApp() app.onModuleLoad() app.draw() app.tab_graffle.raphael.connect() - app.tab_events.raphael.connect() + app.tab_events.raphael.connect() pyjd.run() diff --git a/examples/raphael/spinner.py b/examples/raphael/spinner.py index 507d09db6..48a31c012 100644 --- a/examples/raphael/spinner.py +++ b/examples/raphael/spinner.py @@ -50,7 +50,7 @@ def draw(self): period = 1000/self.numSectors self._timer = Timer(notify=self) - self._timer.scheduleRepeating(period) + self._timer.scheduleRepeating(period) def onTimer(self, timerID): """ Respond to our timer firing. @@ -61,7 +61,7 @@ def onTimer(self, timerID): ############################################################################# -if __name__ == "__main__": +if __name__ == "__main__": pyjd.setup("public/spinner.html") spinner=Spinner() RootPanel().add(spinner) diff --git a/examples/shell/Popups.py b/examples/shell/Popups.py index 78abfed9c..87a909f52 100644 --- a/examples/shell/Popups.py +++ b/examples/shell/Popups.py @@ -40,15 +40,15 @@ def __init__(self, identifier, autoHide=None, modal=False, rootpanel=None): self.dragStartX = 0 self.dragStartY = 0 self.panel = FlexTable() - + self.closeButton = Image("images/cancel.png") self.closeButton.addClickListener(self) dock = DockPanel() dock.setSpacing(0) - + dock.add(self.closeButton, DockPanel.EAST) dock.add(self.caption, DockPanel.WEST) - + dock.setCellHorizontalAlignment(self.closeButton, HasAlignment.ALIGN_RIGHT) dock.setCellHorizontalAlignment(self.caption, HasAlignment.ALIGN_LEFT) dock.setCellWidth(self.caption, "100%") @@ -189,14 +189,14 @@ def __init__(self, identifier, title, iframe): #closeButton = Button("Close", self) #msg = HTML("<center>IFRAME:</center>", True) self.iframe.setStyleName("gwt-DialogFrame") - + self.dock = DockPanel() self.dock.setSpacing(4) - + #dock.add(closeButton, DockPanel.SOUTH) #dock.add(msg, DockPanel.NORTH) self.dock.add(self.iframe, DockPanel.CENTER) - + #dock.setCellHorizontalAlignment(closeButton, HasAlignment.ALIGN_RIGHT) self.dock.setCellWidth(self.iframe, "100%") self.dock.setWidth("100%") @@ -212,7 +212,7 @@ def onClick(self, sender): def set_width(self, width): - self.iframe.setWidth("%dpx" % width) + self.iframe.setWidth("%dpx" % width) def set_height(self, height): self.iframe.setHeight("%dpx" % height) diff --git a/examples/shell/Screen.py b/examples/shell/Screen.py index b5005ad17..dd84e3814 100644 --- a/examples/shell/Screen.py +++ b/examples/shell/Screen.py @@ -18,7 +18,7 @@ def onMouseDown(self, sender, x, y): #log.debug("down %d %d" % (x, y)) DialogBoxModal.onMouseDown(self, sender, x, y) self.dragged = False - + def onMouseMove(self, sender, x, y): #log.debug("move %d %d" % (x, y)) if self.dragStartX != x or self.dragStartY != y: @@ -84,7 +84,7 @@ def raise_app(self, app): self.set_app_zindex(app.identifier, app_zi) def raise_or_lower(self, app): - + app_zi = self.window_zindex[app.identifier] if app_zi != len(self.window)-1: self.raise_app(app) @@ -92,7 +92,7 @@ def raise_or_lower(self, app): self.lower_app(app) def close_app(self, app): - + app_zi = self.window_zindex[app.identifier] for t in self.window_zindex.keys(): w = self.window[t] diff --git a/examples/shell/Shell.py b/examples/shell/Shell.py index 2d252b647..7d553c152 100644 --- a/examples/shell/Shell.py +++ b/examples/shell/Shell.py @@ -87,7 +87,7 @@ def importDone(self): g = mod.AppInit() a = self.screen.add_app(g, self.loading_desc, 400, 300) a.show() - + self.loading_desc = None self.loading_app = None diff --git a/examples/shell/textconsole.py b/examples/shell/textconsole.py index 277d8065d..1defa63c6 100644 --- a/examples/shell/textconsole.py +++ b/examples/shell/textconsole.py @@ -32,7 +32,7 @@ def _get_label(self, x, y): txt = Label(' ') self.add(txt, xpos, ypos) self.text[x][y] = txt - + return self.text[x][y] def setChar(self, x, y, char): @@ -45,7 +45,7 @@ def setWidth(self, width): self.fontsize = math.floor(width / self.cols) AbsolutePanel.setWidth(self, "%dpx" % (self.cols*self.fontsize)) - ratio = self.fontsize / self.fontheight + ratio = self.fontsize / self.fontheight DOM.setStyleAttribute(self.getElement(), 'fontSizeAdjust', str(ratio)) #log.debug(str(ratio)) diff --git a/examples/showcase/pyColourize.py b/examples/showcase/pyColourize.py index b15b4526f..76a9136e0 100644 --- a/examples/showcase/pyColourize.py +++ b/examples/showcase/pyColourize.py @@ -1,8 +1,8 @@ ###################################################################### # PySourceColor -# A hacked up version of the MoinMoin python parser that +# A hacked up version of the MoinMoin python parser that # was originally submitted / written by Jurgen Hermann to ASPN. -# This does not create w3c valid html, but it works on every +# This does not create w3c valid html, but it works on every # browser i've tried so far.(I.E.,Mozilla/Firefox,Opera,wxHTML). # After experimenting with diffrent html vs CSS + html # I settled on plain old html because it works! @@ -20,7 +20,7 @@ __version__ = "ver.1" __date__ = '2 August 2004' __author__ = "M.E.Farmer Jr." -__credits__ = '''This was originally submitted / written by Jurgen Hermann +__credits__ = '''This was originally submitted / written by Jurgen Hermann to ASPN python recipes. I found it in 2003 and integrated it into an editor. Recent refactoring led me to seperate it. I decided to polish it up a little and release it in the hope it would be useful. @@ -32,13 +32,13 @@ _ = (u'uni',u'''uni''',u"uni",u"""uni""")##Unicode test # Do not edit -_DOUBLECOMMENT = token.NT_OFFSET + 1 +_DOUBLECOMMENT = token.NT_OFFSET + 1 _CLASS = token.NT_OFFSET + 2 -_DEF = token.NT_OFFSET + 3 -_TEXT = token.NT_OFFSET + 4 -_KEYWORD = token.NT_OFFSET + 5 -_SINGLEQUOTE = token.NT_OFFSET + 6 -_DOUBLEQUOTE = token.NT_OFFSET + 7 +_DEF = token.NT_OFFSET + 3 +_TEXT = token.NT_OFFSET + 4 +_KEYWORD = token.NT_OFFSET + 5 +_SINGLEQUOTE = token.NT_OFFSET + 6 +_DOUBLEQUOTE = token.NT_OFFSET + 7 _TRIPLESINGLEQUOTE = token.NT_OFFSET + 8 _TRIPLEDOUBLEQUOTE = token.NT_OFFSET + 9 _BACKGROUND = token.NT_OFFSET + 10 @@ -53,13 +53,13 @@ _Null = { token.ERRORTOKEN: '#FF8080',# no edit - token.STRING: '#000000',# no edit + token.STRING: '#000000',# no edit _TEXT: '#000000',# no edit token.NAME: '#000000',# All Text token.NUMBER: 'b#000000',# 0->10 token.OP: 'b#000000',# ()<>=!.:;^>%, etc... tokenize.COMMENT: 'i#000000',# There are 2 types of comment - _DOUBLECOMMENT: '#000000',## Like this + _DOUBLECOMMENT: '#000000',## Like this _CLASS: 'bu#000000',# Class name _DEF: 'b#000000',# Def name _KEYWORD: 'b#000000',# Python keywords @@ -72,13 +72,13 @@ _Dark = { token.ERRORTOKEN: '#FF8080',# no edit - token.STRING: '#FFFFFF',# no edit + token.STRING: '#FFFFFF',# no edit _TEXT: '#000000',# no edit token.NAME: '#ffffff',# All Text token.NUMBER: '#FF0000',# 0->10 token.OP: 'b#FAF785',# Operators ()<>=!.:;^>%, etc... tokenize.COMMENT: 'i#45FCA0',# There are 2 types of comment - _DOUBLECOMMENT: '#A7C7A9',## Like this + _DOUBLECOMMENT: '#A7C7A9',## Like this _CLASS: 'b#B599FD',# Class name _DEF: 'b#EBAE5C',# Def name _KEYWORD: 'b#8680FF',# Python keywords @@ -89,16 +89,16 @@ _BACKGROUND: '#000000',# Page background color } - + _Lite = { token.ERRORTOKEN: '#FF8080',# no edit - token.STRING: '#000000',# no edit + token.STRING: '#000000',# no edit _TEXT: '#000000',# no edit token.NAME: '#000000',# All Text token.NUMBER: '#FF2200',# 0->10 token.OP: 'b#303000',# Operators ()<>=!.:;^>%, etc... tokenize.COMMENT: '#007F00',# There are 2 types of comment - _DOUBLECOMMENT: '#606060',## Like this + _DOUBLECOMMENT: '#606060',## Like this _CLASS: '#0000FF',# Class name _DEF: 'b#BF9B00',# Def name _KEYWORD: 'b#0000AF',# Python keywords @@ -111,13 +111,13 @@ _Idle = { token.ERRORTOKEN: '#FF8080',# no edit - token.STRING: '#000000',# no edit + token.STRING: '#000000',# no edit _TEXT: '#000000',# no edit token.NAME: '#000000',# All Text token.NUMBER: '#000000',# 0->10 token.OP: '#000000',# Operators ()<>=!.:;^>%, etc... tokenize.COMMENT: '#DD0000',# There are 2 types of comment - _DOUBLECOMMENT: '#DD0000',## Like this + _DOUBLECOMMENT: '#DD0000',## Like this _CLASS: '#0000FF',# Class name _DEF: '#0000FF',# Def name _KEYWORD: '#FF7700',# Python keywords @@ -136,7 +136,7 @@ token.NUMBER: '#008080',# 0->10 token.OP: '#000000',# ()<>=!.:;^>%, etc... tokenize.COMMENT: '#007F00',# There are 2 types of comment - _DOUBLECOMMENT: '#7F7F7F',## Like this + _DOUBLECOMMENT: '#7F7F7F',## Like this _CLASS: 'b#0000FF',# Class name _DEF: 'b#007F7F',# Def name _KEYWORD: 'b#000080',# Python keywords @@ -149,13 +149,13 @@ _Eriks_Style = { token.ERRORTOKEN: '#FF8080',# no edit - token.STRING: '#000000',# no edit + token.STRING: '#000000',# no edit _TEXT: '#000000',# no edit token.NAME: '#000000',# All Text token.NUMBER: '#FF2200',# 0->10 token.OP: 'b#303000',# Operators ()<>=!.:;^>%, etc... tokenize.COMMENT: '#007F00',# There are 2 types of comment - _DOUBLECOMMENT: '#606060',## Like this + _DOUBLECOMMENT: '#606060',## Like this _CLASS: '#0000FF',# Class name _DEF: '#0000FF',# Def name _KEYWORD: 'b#0000AF',# Python keywords @@ -178,14 +178,14 @@ def Usage(): python PySourceColor.py --in=c:/myDir/my.py --out=c:/myDir --color=Lite --show # Using short options w/out = python PySourceColor.py -i c:/myDir/ -c Idle - # Using any mix + # Using any mix python PySourceColor.py --in _ -o=c:/myDir --show ------------------------------------------------------------------------------- This module is designed to colorize python source code. It is a hacked version of MoinMoin python parser recipe. -h or --help Display this help message. - -i or --in + -i or --in Input file or dir. (Use any of these for the cwdir . , _ , this) -o or --out Optional, output dir for the colorized source @@ -201,11 +201,11 @@ def Usage(): """ def Main(): - '''This code gathers the command line arguments + '''This code gathers the command line arguments and tries to do something reasonable with them ''' try: - # try to get command line args + # try to get command line args opts, args = getopt.getopt(sys.argv[1:], "hsi:o:c:", ["help", "show", "input=", "out=", "color="]) except getopt.GetoptError: @@ -272,7 +272,7 @@ def WebAll(sourcePath, outdir=None, colors=None, show=0): def WebIt(sourcePath, outdir=None, colors=None, show=0): ''' Converts python source to html. ''' - print" Converting %s into HTML" % sourcePath + print" Converting %s into HTML" % sourcePath if colors is None: # Default colorscheme colors = _Dark @@ -306,7 +306,7 @@ def WalkDir(dir): GLOB_PATTERN = os.path.join(dir, "*.[p][y]*") pathlist = glob.glob(GLOB_PATTERN) # Now filter out all but py and pyw - filterlist = [x for x in pathlist + filterlist = [x for x in pathlist if x.endswith('.py') or x.endswith('.pyw')] if filterlist != []: @@ -354,7 +354,7 @@ def format(self, formatter, form): self.doPageStart() # Parse the source. - ## Tokenize calls the __call__ + ## Tokenize calls the __call__ ## function for each token till done. try: tokenize.tokenize(text.readline, self) @@ -403,7 +403,7 @@ def __call__(self, toktype, toktext, (srow,scol), (erow,ecol), line): # Sets the color if it was a class or def name if self.ClassFlag: toktype = _CLASS - self.ClassFlag = 0 + self.ClassFlag = 0 elif self.DefFlag: toktype = _DEF self.DefFlag = 0 @@ -447,7 +447,7 @@ def __call__(self, toktype, toktext, (srow,scol), (erow,ecol), line): splitpoint = color.find('#') tags = color[:splitpoint].lower() color = color[splitpoint:] - + # Check for styles and set them if needed..(b=bold, i=italics) if 'b' in tags: otherstart += '<b>' @@ -480,7 +480,7 @@ def doPageStart(self): # Get background color and check for styles and ignore all but b,i,u color = self.colors.get(_BACKGROUND, self.colors[_TEXT]) color = color[color.find('#'):] - if color[:1] != '#': + if color[:1] != '#': self.out.write('</head><body bgcolor="#000000">\n') else: self.out.write('</head><body bgcolor="%s">\n'% color) diff --git a/examples/showcase/src/demos_panels/formPanel.py b/examples/showcase/src/demos_panels/formPanel.py index fa1e8170b..9e020c33f 100644 --- a/examples/showcase/src/demos_panels/formPanel.py +++ b/examples/showcase/src/demos_panels/formPanel.py @@ -26,8 +26,8 @@ uploaded. Also, note that FormPanel is a subclass of SimplePanel. This means that if you -want a form with more than one widget, you will need to add a subclass of -ComplexPanel as the child widget of the FormPanel. An instance of +want a form with more than one widget, you will need to add a subclass of +ComplexPanel as the child widget of the FormPanel. An instance of VerticalPanel is used in this example. """ from pyjamas.ui.SimplePanel import SimplePanel diff --git a/examples/showcase/src/demos_panels/scrollPanel.py b/examples/showcase/src/demos_panels/scrollPanel.py index 161931efe..8e02f9172 100644 --- a/examples/showcase/src/demos_panels/scrollPanel.py +++ b/examples/showcase/src/demos_panels/scrollPanel.py @@ -26,7 +26,7 @@ def __init__(self): vert = VerticalPanel() vert.setSpacing("10px") self.add(vert) - + panel = ScrollPanel(Size=("300px", "100px")) contents = HTML("<b>Tao Te Ching, Chapter One</b><p>" + diff --git a/examples/showcase/src/demos_widgets/textArea.py b/examples/showcase/src/demos_widgets/textArea.py index f85ff5813..fe8f85945 100644 --- a/examples/showcase/src/demos_widgets/textArea.py +++ b/examples/showcase/src/demos_widgets/textArea.py @@ -43,7 +43,7 @@ def onBrowserEvent(self, event): self.doneHandler.done() else: self.autoHeight() #if not ctrl-enter, adjust height - + def autoHeight(self): #here is some really weak code to calculate the height of the textarea. #its not very accurate, im sure you can do better! remember to "import math" diff --git a/examples/showcase/src/uiHelpers.py b/examples/showcase/src/uiHelpers.py index b491685d3..b9184f781 100644 --- a/examples/showcase/src/uiHelpers.py +++ b/examples/showcase/src/uiHelpers.py @@ -21,7 +21,7 @@ def indent(contents, all=None, left=None, right=None, top=None, bottom=None, """ Add a wrapper around the given contents to indent it. The parameters are as follows: - + 'contents' The contents to indent. This should be a widget or a panel. diff --git a/examples/slideshow/Slide.py b/examples/slideshow/Slide.py index d382aaf7a..fd7fa3b61 100644 --- a/examples/slideshow/Slide.py +++ b/examples/slideshow/Slide.py @@ -30,7 +30,7 @@ def urlmap(txt): txt = esc(beg) + "<a href='%s'>" % url txt += "%s</a>" % esc(url) + urlmap(end) return txt - + def ts(txt): l = txt.split('\n') r = [] @@ -52,7 +52,7 @@ def __init__(self): def onShow(self): if self.loaded: - return + return name = self.name.replace(" ", "_") name = name.lower() @@ -78,7 +78,7 @@ def setSlide(self, text): txt += line txt += "\n" continue - + line = line.strip() ul_line = False ul_line2 = False @@ -129,13 +129,13 @@ def onError(self, text, code): self.vp.add(HTML("TODO: Slide '%s' not loaded" % self.name)) self.vp.add(HTML(text)) self.vp.add(HTML(code)) - + def onProgress(self, event): self.vp.clear() self.vp.add(HTML("Progress: %s" % self.name)) self.vp.add(HTML("%s" % str(event.loaded))) self.vp.add(HTML("%s" % str(event.total))) - + def init(name, desc): return SinkInfo(name, desc, Slide) diff --git a/examples/slideshow/Slideshow.py b/examples/slideshow/Slideshow.py index 72c0c78d5..af04f3661 100644 --- a/examples/slideshow/Slideshow.py +++ b/examples/slideshow/Slideshow.py @@ -34,7 +34,7 @@ def onModuleLoad(self): self.sink_list=SinkList() self.panel=DockPanel() self.b=Button("load", self) - + self.sinkContainer = DockPanel() self.sinkContainer.setStyleName("ks-Sink") @@ -99,7 +99,7 @@ def show(self, info, affectHistory): self.sinkContainer.setCellHeight(self.curSink, "100%") self.sinkContainer.setCellVerticalAlignment(self.curSink, HasAlignment.ALIGN_TOP) self.curSink.onShow() - + def loadSinks(self): HTTPRequest().asyncGet("slides.txt", SlideListLoader(self)) diff --git a/examples/splitpanel/SplitPanel.py b/examples/splitpanel/SplitPanel.py index 125f66deb..f784e2c40 100644 --- a/examples/splitpanel/SplitPanel.py +++ b/examples/splitpanel/SplitPanel.py @@ -1,45 +1,45 @@ -import pyjd # dummy in pyjs - -from pyjamas.ui.RootPanel import RootPanel -from pyjamas.ui.HTML import HTML -from pyjamas.ui.Label import Label -from pyjamas.ui import HasAlignment -from pyjamas.ui.Button import Button -from pyjamas import Window - -from pyjamas.ui.VerticalSplitPanel import VerticalSplitPanel -from pyjamas.ui.HorizontalSplitPanel import HorizontalSplitPanel - - -class SplitPanel: - - def onModuleLoad(self): - self.vertpanel = VerticalSplitPanel() - self.vertpanel.setSize("500px", "350px") - self.vertpanel.setSplitPosition("30%") - self.vertpanel.setStyleAttribute("background", "red") - - self.horzpanel = HorizontalSplitPanel() - self.horzpanel.setSize("500px", "350px") - self.horzpanel.setSplitPosition("50%") - self.horzpanel.setStyleAttribute("background", "yellow") - - randomText = "" - for i in range(200): - randomText += "hello %d " % i - - self.vertpanel.setTopWidget(HTML(randomText)) - self.vertpanel.setBottomWidget(HTML(randomText)) - - self.horzpanel.setLeftWidget(HTML(randomText)) - self.horzpanel.setRightWidget(HTML(randomText)) - - RootPanel().add(self.vertpanel) - RootPanel().add(self.horzpanel) - - -if __name__ == '__main__': - pyjd.setup("./public/SplitPanel.html") - app = SplitPanel() - app.onModuleLoad() - pyjd.run() +import pyjd # dummy in pyjs + +from pyjamas.ui.RootPanel import RootPanel +from pyjamas.ui.HTML import HTML +from pyjamas.ui.Label import Label +from pyjamas.ui import HasAlignment +from pyjamas.ui.Button import Button +from pyjamas import Window + +from pyjamas.ui.VerticalSplitPanel import VerticalSplitPanel +from pyjamas.ui.HorizontalSplitPanel import HorizontalSplitPanel + + +class SplitPanel: + + def onModuleLoad(self): + self.vertpanel = VerticalSplitPanel() + self.vertpanel.setSize("500px", "350px") + self.vertpanel.setSplitPosition("30%") + self.vertpanel.setStyleAttribute("background", "red") + + self.horzpanel = HorizontalSplitPanel() + self.horzpanel.setSize("500px", "350px") + self.horzpanel.setSplitPosition("50%") + self.horzpanel.setStyleAttribute("background", "yellow") + + randomText = "" + for i in range(200): + randomText += "hello %d " % i + + self.vertpanel.setTopWidget(HTML(randomText)) + self.vertpanel.setBottomWidget(HTML(randomText)) + + self.horzpanel.setLeftWidget(HTML(randomText)) + self.horzpanel.setRightWidget(HTML(randomText)) + + RootPanel().add(self.vertpanel) + RootPanel().add(self.horzpanel) + + +if __name__ == '__main__': + pyjd.setup("./public/SplitPanel.html") + app = SplitPanel() + app.onModuleLoad() + pyjd.run() diff --git a/examples/tabpanelwidget/Tabs.py b/examples/tabpanelwidget/Tabs.py index e3514d9f6..ee930b50f 100644 --- a/examples/tabpanelwidget/Tabs.py +++ b/examples/tabpanelwidget/Tabs.py @@ -74,7 +74,7 @@ def onModuleLoad(self): def createImage(self, imageUrl): image = Image(imageUrl) image.setStyleName("ks-images-Image") - + p = VerticalPanel() p.setHorizontalAlignment(HasAlignment.ALIGN_CENTER) p.setVerticalAlignment(HasAlignment.ALIGN_MIDDLE) diff --git a/examples/timerdemo/timerdemo.py b/examples/timerdemo/timerdemo.py index aab0328d5..c900e148c 100644 --- a/examples/timerdemo/timerdemo.py +++ b/examples/timerdemo/timerdemo.py @@ -54,10 +54,10 @@ class Clock: happens when you click on the button. ''' - + start_txt = 'Click to start the clock' stop_txt = 'Click to stop the clock' - + def __init__(self): # the button @@ -129,7 +129,7 @@ def run(self): else: self.create_popup() self.reset() - + def reset(self): # reset to starting state self.setHTML('Click for countdown popup') @@ -234,7 +234,7 @@ def onControlValueChanged(self, sender, old, new): # no it's being reset self.__label.setText(str(new) + ' sec') self.onTimer(self.timer) - + def randomcolor(self): # randomize the color and set the panel accordingly diff --git a/examples/timesheet/__main__.py b/examples/timesheet/__main__.py index 529f832a7..8538ab820 100644 --- a/examples/timesheet/__main__.py +++ b/examples/timesheet/__main__.py @@ -14,7 +14,7 @@ ], downloads=[ dict( - url='http://puremvc.org/pages/downloads/Python/PureMVC_Python.zip', + url='http://puremvc.org/pages/downloads/Python/PureMVC_Python.zip', dst=os.path.join(puremvc, 'PureMVC_Python.zip'), unzip=True, ) diff --git a/examples/timesheet/model/TimeProxy.py b/examples/timesheet/model/TimeProxy.py index 78322c234..01f2c581f 100644 --- a/examples/timesheet/model/TimeProxy.py +++ b/examples/timesheet/model/TimeProxy.py @@ -8,7 +8,7 @@ import time class TimeProxy(puremvc.patterns.proxy.Proxy): - + NAME = "TimeProxy" def __init__(self): super(TimeProxy, self).__init__(TimeProxy.NAME, []) @@ -24,7 +24,7 @@ def getDateEntries(self, date): def setDateEntries(self, date, entries): self.data[date] = entries - + def addItem(self, date, item): if not self.data.has_key(date): self.data[date] = [] diff --git a/examples/timesheet/model/vo/TimeVO.py b/examples/timesheet/model/vo/TimeVO.py index 1ef008dc9..a8bae5cb2 100644 --- a/examples/timesheet/model/vo/TimeVO.py +++ b/examples/timesheet/model/vo/TimeVO.py @@ -6,7 +6,7 @@ class TimeVO(object): end = None project = None description = None - + def __init__(self, start, end, project, description = ''): self.start = start self.end = end diff --git a/examples/timesheet/view/DatePickerMediator.py b/examples/timesheet/view/DatePickerMediator.py index 6961316df..f11af423f 100644 --- a/examples/timesheet/view/DatePickerMediator.py +++ b/examples/timesheet/view/DatePickerMediator.py @@ -27,5 +27,5 @@ def handleNotification(self, note): def displayDay(self, sender=None): self.viewComponent.displayDay() - self.sendNotification(Notification.DATE_SELECTED, + self.sendNotification(Notification.DATE_SELECTED, self.viewComponent.date) diff --git a/examples/timesheet/view/MenuMediator.py b/examples/timesheet/view/MenuMediator.py index d5b42bf8e..f5a55914a 100644 --- a/examples/timesheet/view/MenuMediator.py +++ b/examples/timesheet/view/MenuMediator.py @@ -58,7 +58,7 @@ def onFileOpen(self, fileLocation = None): dlg = None def onOpen(sender): - self.sendNotification(Notification.FILE_LOADED, + self.sendNotification(Notification.FILE_LOADED, (dlg.filename, dlg.data)) fileLocation = self.checkFileLocation(fileLocation) diff --git a/examples/timesheet/view/TimeGridMediator.py b/examples/timesheet/view/TimeGridMediator.py index 6ac6bbc59..e30ee6699 100644 --- a/examples/timesheet/view/TimeGridMediator.py +++ b/examples/timesheet/view/TimeGridMediator.py @@ -52,7 +52,7 @@ def handleNotification(self, note): def onDateSelected(self, date): if not self.viewComponent.date is None and self.viewComponent.dirty: - self.timeProxy.setDateEntries(self.viewComponent.date, + self.timeProxy.setDateEntries(self.viewComponent.date, self.viewComponent.getEntries()) self.viewComponent.date = date self.viewComponent.setEntries(self.timeProxy.getDateEntries(self.viewComponent.date)) diff --git a/examples/timesheet/view/components/Grid.py b/examples/timesheet/view/components/Grid.py index cf75d02b5..cdd3ef027 100644 --- a/examples/timesheet/view/components/Grid.py +++ b/examples/timesheet/view/components/Grid.py @@ -59,4 +59,4 @@ def styleRow(self, row, selected): self.getRowFormatter().addStyleName(row, "gwt-SelectedRow") else: self.getRowFormatter().removeStyleName(row, "gwt-SelectedRow") - + diff --git a/examples/timesheet/view/components/Summary.py b/examples/timesheet/view/components/Summary.py index 994ed4f90..f3bbfed5e 100644 --- a/examples/timesheet/view/components/Summary.py +++ b/examples/timesheet/view/components/Summary.py @@ -13,7 +13,7 @@ class Summary(FlexTable): - columns = [("Time", 5, 5), + columns = [("Time", 5, 5), ("Description", None, 60), ] rows = 0 diff --git a/examples/timesheet/view/components/TimeGrid.py b/examples/timesheet/view/components/TimeGrid.py index 1ad420e46..31d7471cd 100644 --- a/examples/timesheet/view/components/TimeGrid.py +++ b/examples/timesheet/view/components/TimeGrid.py @@ -14,9 +14,9 @@ class TimeGrid(FlexTable): - columns = [("From", 5, 5), - ("To", 5, 5), - ("Project", None, 20), + columns = [("From", 5, 5), + ("To", 5, 5), + ("Project", None, 20), ("Description", None, 40), ] emptyTimeVO = TimeVO("", "", "", "") @@ -99,7 +99,7 @@ def selectCell(self, row, col): self.currentCol = col self.getWidget(self.currentRow, self.currentCol).setFocus(True) return - # Now we're moving to new postition, just make sure + # Now we're moving to new postition, just make sure # that the previous cells are filled in correctly if not self.checkCell(self.currentRow, self.currentCol, True): # Nope. We won't move @@ -205,7 +205,7 @@ def checkHHMM(self, text): MM = "00" return "%s:%s" % (HH, MM) raise ValueError("Invalid format '%s'" % text) - + def autoFill(self, row, col): widget = self.getWidget(row, col) diff --git a/examples/toggle/Toggle.py b/examples/toggle/Toggle.py index 8caf92d60..752ca362d 100644 --- a/examples/toggle/Toggle.py +++ b/examples/toggle/Toggle.py @@ -15,9 +15,9 @@ class Toggle: def onModuleLoad(self): - + self.label = Label("Not set yet") - + self.button = Button("Probe button", self) self.image_up = Image("./images/logo.png") self.image_up3 = Image("./images/logo.png") @@ -26,28 +26,28 @@ def onModuleLoad(self): self.toggle = ToggleButton(self.image_up, self.image_down, self) self.toggle2 = ToggleButton("up", "down", getattr(self, "onToggleUD")) self.push = PushButton(self.image_up3, self.image_down3) - + self.vpanel = VerticalPanel() self.togglePanel = HorizontalPanel() self.togglePanel.setSpacing(10) - + self.togglePanel.add(self.toggle) self.togglePanel.add(self.toggle2) self.togglePanel.add(self.push) - + self.vpanel.add(self.label) self.vpanel.add(self.button) self.vpanel.add(self.togglePanel) - + RootPanel().add(self.vpanel) self.i = False - + def onToggleUD(self, sender): self.label.setText(" Toggle2 isdown: "+str(self.toggle2.isDown())) def onClick(self, sender): if sender == self.button: - if self.i: + if self.i: self.i = False text = ">>>>UP<<<<" self.toggle.setCurrentFace(self.toggle.getUpFace()) diff --git a/examples/treeitemcheckbox/TreeItemTest.py b/examples/treeitemcheckbox/TreeItemTest.py index 12a16e5ce..7e4333a0a 100644 --- a/examples/treeitemcheckbox/TreeItemTest.py +++ b/examples/treeitemcheckbox/TreeItemTest.py @@ -1,5 +1,5 @@ # Copyright (C) 2011 Vsevolod Fedorov <vsevolod.fedorov@gmail.com> -# License: Apache2 +# License: Apache2 # demonstrates issue #628 http://code.google.com/p/pyjamas/issues/detail?id=638 import pyjd # this is dummy in pyjs. diff --git a/examples/uitest/EventTest.py b/examples/uitest/EventTest.py index 80364e63b..0f3b5b096 100644 --- a/examples/uitest/EventTest.py +++ b/examples/uitest/EventTest.py @@ -27,6 +27,6 @@ def testButtonClick(self): self.write_test_output('removeButton') def lastTestChecks(self): - + self.assertTrue(self.buttonClickTestOccurred, 'testButtonClick failed') diff --git a/examples/uitest/UnitTest.py b/examples/uitest/UnitTest.py index 4fd9128da..1d899bc1b 100644 --- a/examples/uitest/UnitTest.py +++ b/examples/uitest/UnitTest.py @@ -176,7 +176,7 @@ def check_start_next_test(self): return # do it again. Timer(100, self) - + def setUp(self): pass diff --git a/examples/uitest/uitest.py b/examples/uitest/uitest.py index 76af74a20..63a92c8f4 100644 --- a/examples/uitest/uitest.py +++ b/examples/uitest/uitest.py @@ -6,7 +6,7 @@ from UnitTest import IN_BROWSER, IN_JS, IN_BROWSER -from DockPanelTest import DockPanelTest +from DockPanelTest import DockPanelTest from LabelTest import LabelTest from DOMTest import DOMTest from EventTest import EventTest @@ -67,6 +67,6 @@ def main(test_gen_out): if hasattr(sys, 'argv'): if len(sys.argv) == 2: test_gen_output_folder = sys.argv[1] - + main(test_gen_output_folder ) diff --git a/examples/uploader/AsyncUpload.py b/examples/uploader/AsyncUpload.py index 72d401c0e..f9b7fbbf6 100644 --- a/examples/uploader/AsyncUpload.py +++ b/examples/uploader/AsyncUpload.py @@ -8,21 +8,21 @@ def onload(evnt=None): localHandler = handler status = xmlHttp.status localHandler.onload(status) - + def onprogress(evnt=None): global xmlHttp, handler localHandler = handler localHandler.onprogress(evnt.loaded, evnt.total) - + def onerror(evnt=None): global xmlHttp, handler localHandler = handler status = xmlHttp.status localHandler.onerror(status) - + xmlHttp.upload.load = onload xmlHttp.upload.progress = onprogress - + xmlHttp.upload.onload = onload xmlHttp.upload.onprogress = onprogress xmlHttp.upload.onerror = onerror @@ -32,7 +32,7 @@ def onerror(evnt=None): try: xmlHttp.open("POST", url, True) JS("""var reader = new FileReader(); - + reader.onload = function(evt) { var fd = new FormData(); fd.append("file", @{{file}}); diff --git a/examples/uploader/Upload.py b/examples/uploader/Upload.py index d9e6362d1..76d922022 100644 --- a/examples/uploader/Upload.py +++ b/examples/uploader/Upload.py @@ -65,7 +65,7 @@ def __init__(self): hPanel.add(Button("Submit", getattr(self, "onBtnClick"))) vPanel.add(hPanel) - + self.simple = CheckBox("Simple mode? ") #self.simple.setChecked(True) vPanel.add(self.simple) @@ -88,7 +88,7 @@ def onBtnClick(self, event): else: el = self.field.getElement() files = getattr(el, 'files') - #TODO implement loop for multiple file uploads + #TODO implement loop for multiple file uploads file = JS("@{{files}}[0]") #otherwise pyjs thinks it's a string? AsyncUpload.asyncUpload(self.url, file, self) diff --git a/examples/widgets/Widgets.py b/examples/widgets/Widgets.py index 74ce99f6d..61451f305 100644 --- a/examples/widgets/Widgets.py +++ b/examples/widgets/Widgets.py @@ -18,14 +18,14 @@ def onModuleLoad(self): if not img_url: img_url = 'images/chrome_clock.png' self.solar = SolarCanvas(img_url) - + RootPanel().add(self.solar) self.onShow() def onShow(self): self.solar.isActive = True self.solar.onTimer() - + def onHide(self): self.solar.isActive = False @@ -37,7 +37,7 @@ def __init__(self, img_url): loadImages([img_url], self) self.width = 150 self.height = 150 - + self.isActive = True self.onTimer() @@ -48,14 +48,14 @@ def onImagesLoaded(self, imagesHandles): self.height = DOM.getIntAttribute(el, "height") self.setWidth("%d" % self.width) self.setHeight("%d" % self.height) - + def onError(self, sender): Window.alert("error of some kind (probably missing image at url)") def onTimer(self, sender=None): if not self.isActive: return - + Timer(1000, self) self.draw() @@ -75,17 +75,17 @@ def draw(self): pi = 3.14159265358979323 if not getattr(self, 'clock', None): return - + self.setGlobalCompositeOperation('destination-over') # clear canvas self.clear() - + self.saveContext() self.setFillStyle(Color('rgba(0,0,0,0.4)')) self.setStrokeStyle(Color('rgba(0,153,255,0.4)')) self.translate(self.width/2,self.height/2) - + secs = self.getTimeSeconds() mins = self.getTimeMinutes() + secs / 60.0 hours = self.getTimeHours() + mins / 60.0 @@ -94,23 +94,23 @@ def draw(self): self.saveContext() self.setFillStyle(Color('rgba(255,0,0,0.4)')) self.rotate( ((2*pi)/60)*secs + pi) - self.fillRect(-1,-(self.width * 0.04),2, self.width * 0.38) + self.fillRect(-1,-(self.width * 0.04),2, self.width * 0.38) self.restoreContext() - + # Minutes self.saveContext() self.rotate( ((2*pi)/60)*mins + pi) - self.fillRect(-1,-1,3,self.width * 0.35) + self.fillRect(-1,-1,3,self.width * 0.35) self.restoreContext() - + # Hours self.saveContext() self.rotate( ((2*pi)/12)*hours + pi) - self.fillRect(-2,-2,4,self.width * 0.2) + self.fillRect(-2,-2,4,self.width * 0.2) self.restoreContext() - + self.restoreContext() - + self.drawImage(self.clock.getElement(),0,0) @@ -120,7 +120,7 @@ def AppInit(): if not img_url: img_url = 'images/chrome_clock.png' solar = SolarCanvas(img_url) - + solar.isActive = True solar.onTimer() diff --git a/examples/xmldoc/XMLload.py b/examples/xmldoc/XMLload.py index 8c1ac4649..40a1ae3d9 100644 --- a/examples/xmldoc/XMLload.py +++ b/examples/xmldoc/XMLload.py @@ -1,5 +1,5 @@ # Modifications to allow execution under pyjd on Windows (mshtml) 2010-09-08 -# See Issue 481 - Copyright (c) Phil Charlesworth 2010 +# See Issue 481 - Copyright (c) Phil Charlesworth 2010 import pyjd from pyjamas.ui.Button import Button @@ -32,7 +32,7 @@ def onTimeout(self, text): class XMLload: def onModuleLoad(self): - + HTTPRequest().asyncGet("contacts.xml", XMLloader(self)) def onError(self, text, code): diff --git a/generate_stdlib.py b/generate_stdlib.py index 24235a1d4..7c74f6a1c 100755 --- a/generate_stdlib.py +++ b/generate_stdlib.py @@ -29,11 +29,11 @@ def copy_tests(dest, src): if not isdir(src): return for p in os.listdir(src): - if (not isdir(join(src, p)) + if (not isdir(join(src, p)) and p.endswith('.py') and not exists(join(dest, p))): shutil.copy2(join(src, p), join(dest, p)) - + def copy_libs(dest, src, src_name, excludes): for p in os.listdir(src): if isdir(join(src, p)): @@ -42,8 +42,8 @@ def copy_libs(dest, src, src_name, excludes): mod_name = p.split('.')[0] else: continue - - if (not exists(join(dest, mod_name)) and + + if (not exists(join(dest, mod_name)) and not exists(join(dest, mod_name + '.py')) and not mod_name in excludes): if isdir(join(src, p)): @@ -51,7 +51,7 @@ def copy_libs(dest, src, src_name, excludes): else: shutil.copy2(join(src, p), join(dest, p)) mod_src[mod_name] = src_name - + def main(): parser = OptionParser() @@ -63,27 +63,27 @@ def main(): "--cpython", dest="cpython", help="Path to CPython libraries") - + options, args = parser.parse_args() - if not options.cpython: + if not options.cpython: cpython_path = dirname(os.__file__) else: cpython_path = options.cpython - + if options.pypy: imports.append(('pypy', options.pypy, pypy_excludes)) - + if cpython_path: imports.append(('cpython', cpython_path, cpython_excludes)) - + if exists(dest_path): shutil.rmtree(dest_path) os.mkdir(dest_path) os.mkdir(join(dest_path, 'test')) - + print ("Exporting data from:") for name, path, exc in imports: - print ("{0}: {1}".format(name, path)) + print ("{0}: {1}".format(name, path)) copy_libs(dest_path, path, name, exc) copy_tests(dest_path, path) @@ -91,7 +91,7 @@ def main(): for mod, src in mod_src.iteritems(): f_mod_src.write("{}:{}\n".format(mod, src)) f_mod_src.close() - - + + if __name__ == '__main__': main() \ No newline at end of file diff --git a/library/__pyjamas__.py b/library/__pyjamas__.py index 658580631..cd0ab0bf5 100644 --- a/library/__pyjamas__.py +++ b/library/__pyjamas__.py @@ -42,10 +42,10 @@ def get_main_frame(): return main_frame def doc(): - return main_frame.getDomDocument() + return main_frame.getDomDocument() def wnd(): - return main_frame.getDomWindow() + return main_frame.getDomWindow() def JS(code): """ try to avoid using this function, it will only give you grief diff --git a/library/dynamic.py b/library/dynamic.py index 977ab1e99..bb5b35578 100644 --- a/library/dynamic.py +++ b/library/dynamic.py @@ -85,10 +85,10 @@ def inject(values, namespace = None, names=None): # # activate_css(str) -# +# # looks for any < link > in the input and sets up a corresponding link node # in the main document. -# +# def activate_css(targetnode): scriptnodes = list(targetnode.getElementsByTagName('link')) @@ -110,10 +110,10 @@ def activate_css(targetnode): # # activate_javascript(str) -# +# # looks for any < script > in the input text and sets up a corresponding # script node in the main document. -# +# def activate_javascript(txt): fileref = DOM.createElement('script') @@ -167,7 +167,7 @@ def ajax_import(url, namespace=None, names=None): names = [] for name in names: name_getter.append("$pyjs$moduleObject['%s'] = %s;" % (name, name)) - + script = """(function ( ) { $pyjs$moduleObject={}; %s; @@ -185,13 +185,13 @@ def ajax_import(url, namespace=None, names=None): # From here, just converted from dynamicajax.js -# +# # pyjs_load_script # # @param url load script url # @param module module name # @param onload text of function to be eval/executed on successful load -# +# def load_script(url, onload, async): wnd().status = ('Loading ' + url) @@ -213,12 +213,12 @@ def onload_fn(): # # ajax_dlink_refresh(oj,url) -# +# # @param id id of element for insert # @param url load url # @param timeout refresh timeout period, ms # @returns readyState -# +# # use these to overrun an existing timeout, so that # we don't end up with several of them! diff --git a/library/pygwt.browser.py b/library/pygwt.browser.py index 75b39a046..785e602f3 100644 --- a/library/pygwt.browser.py +++ b/library/pygwt.browser.py @@ -19,17 +19,17 @@ def getModuleBaseURL(): // this is intentionally not using $doc, because we want // the module's own url var s = document.location.href; - + // Pull off any hash. var i = s.indexOf('#'); if (i != -1) s = s.substring(0, i); - + // Pull off any query string. i = s.indexOf('?'); if (i != -1) s = s.substring(0, i); - + // Rip off everything after the last slash. i = s.lastIndexOf('/'); if (i != -1) diff --git a/library/pyjamas/Canvas/CanvasGradientImplDefault.py b/library/pyjamas/Canvas/CanvasGradientImplDefault.py index e4f4af044..998e8d22e 100644 --- a/library/pyjamas/Canvas/CanvasGradientImplDefault.py +++ b/library/pyjamas/Canvas/CanvasGradientImplDefault.py @@ -23,21 +23,21 @@ * Native canvas gradients. """ class CanvasGradientImplDefault: - + def __init__(self): self.nativeGradient = None - + def addColorStop(self, offset, color): self.addNativeColorStop(offset, str(color)) - + def getObject(self): return self.nativeGradient - + def addNativeColorStop(self, offset, color): self.nativeGradient.addColorStop(offset, color); - + def setNativeGradient(self, grad): self.nativeGradient = grad - + diff --git a/library/pyjamas/Canvas/CanvasGradientImplIE6.py b/library/pyjamas/Canvas/CanvasGradientImplIE6.py index 7962e05e0..47124f7ad 100644 --- a/library/pyjamas/Canvas/CanvasGradientImplIE6.py +++ b/library/pyjamas/Canvas/CanvasGradientImplIE6.py @@ -1,7 +1,7 @@ """ * Copyright 2008 Google Inc. * Copyright 2011 Bob Hampton -* +* * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at @@ -40,9 +40,9 @@ def __init__(self, x0, y0, x1, y1): self.angle = 90 else: self.angle = int(math.atan(self.dx/self.dy) * 180 / math.pi) + 180 - + self.colorStops = [] - + def addColorStop(self, offset, color): newColorStop = ColorStop(offset, color) for i in range(len(self.colorStops)): @@ -50,10 +50,10 @@ def addColorStop(self, offset, color): if offset < cs.offset: self.colorStops.append(i, newColorStop) return - + self.colorStops.append(newColorStop) - - + + """* * Creates an equivalent copy of this Gradient object. * diff --git a/library/pyjamas/Canvas/Color.py b/library/pyjamas/Canvas/Color.py index 2cd3a1ffb..231792af8 100644 --- a/library/pyjamas/Canvas/Color.py +++ b/library/pyjamas/Canvas/Color.py @@ -21,7 +21,7 @@ * of the specified color for easy compatibility with various APIs """ class Color: - + """* * Create a using a valid CSSString. * We do not do any validation so be careful! @@ -50,10 +50,10 @@ def __init__(self, r, g=None, b=None, a=None): self.colorStr = "rgb(%d,%d,%d)" % (r, g, b) else: self.colorStr = "rgba(%d,%d,%d,%f)" % (r, g, b, a) - + def __str__(self): return self.colorStr - + """ diff --git a/library/pyjamas/Canvas/ColorStop.py b/library/pyjamas/Canvas/ColorStop.py index 5a2e14072..48f42164a 100644 --- a/library/pyjamas/Canvas/ColorStop.py +++ b/library/pyjamas/Canvas/ColorStop.py @@ -22,11 +22,11 @@ * to a color stop for color gradients. Only needed for IE impl. """ class ColorStop: - + def __init__(self, myOffset, myColor): self.offset = myOffset self.color = myColor - + def cloneColorStop(self): return ColorStop(self.offset, Color(str(self.color()))) diff --git a/library/pyjamas/Canvas/GWTCanvas.ie6.py b/library/pyjamas/Canvas/GWTCanvas.ie6.py index 5c12d087c..d3a7459f7 100644 --- a/library/pyjamas/Canvas/GWTCanvas.ie6.py +++ b/library/pyjamas/Canvas/GWTCanvas.ie6.py @@ -1,5 +1,5 @@ class GWTCanvas(Widget): - + def getCanvasImpl(self): return GWTCanvasImplIE6() def createLinearGradient(self, x0, y0, x1, y1): diff --git a/library/pyjamas/Canvas/GWTCanvas.mshtml.py b/library/pyjamas/Canvas/GWTCanvas.mshtml.py index 5c12d087c..d3a7459f7 100644 --- a/library/pyjamas/Canvas/GWTCanvas.mshtml.py +++ b/library/pyjamas/Canvas/GWTCanvas.mshtml.py @@ -1,5 +1,5 @@ class GWTCanvas(Widget): - + def getCanvasImpl(self): return GWTCanvasImplIE6() def createLinearGradient(self, x0, y0, x1, y1): diff --git a/library/pyjamas/Canvas/GWTCanvas.py b/library/pyjamas/Canvas/GWTCanvas.py index bcd4317f9..0cb5b9e5a 100644 --- a/library/pyjamas/Canvas/GWTCanvas.py +++ b/library/pyjamas/Canvas/GWTCanvas.py @@ -42,7 +42,7 @@ * </p> """ class GWTCanvas(FocusWidget): - + """* * Creates a GWTCanvas element. Element type depends on deferred binding. * Default is CANVAS HTML5 DOM element. In the case of IE it should be VML. @@ -60,13 +60,13 @@ class GWTCanvas(FocusWidget): """ def __init__(self, coordX=300, coordY=150, pixelX=300, pixelY=150, **kwargs): - + """ * Impl Instance. Compiler should statify all the methods, so we * do not end up with duplicate code for each canvas instance. """ self.impl = self.getCanvasImpl() - + self.coordHeight = 0 self.coordWidth = 0 focusable = Focus.createFocusable() @@ -77,13 +77,13 @@ def __init__(self, coordX=300, coordY=150, pixelX=300, pixelY=150, self.setPixelWidth(pixelX) self.setPixelHeight(pixelY) self.setCoordSize(coordX, coordY) - + def getCanvasElement(self): return self.canvas def getCanvasImpl(self): return GWTCanvasImplDefault() - + def setWidth(self, width): self.setPixelWidth(width) @@ -104,15 +104,15 @@ def setHeight(self, height): """ def arc(self, x, y, radius, startAngle, endAngle, antiClockwise): self.impl.arc(x, y, radius, startAngle, endAngle, antiClockwise) - - + + """* * Erases the current path and prepares it for a path. """ def beginPath(self): self.impl.beginPath() - - + + """* * Clears the entire canvas. """ @@ -120,16 +120,16 @@ def clear(self): # we used local references instead of looking up the attributes # on the DOM element self.impl.clear(self.coordWidth, self.coordHeight) - - + + """* * Closes the current path. "Closing" simply means that a line is drawn from * the last element in the path back to the first. """ def closePath(self): self.impl.closePath() - - + + """* * * Creates a LinearGradient Object for use as a fill or stroke style. @@ -142,8 +142,8 @@ def closePath(self): """ def createLinearGradient(self, x0, y0, x1, y1): return LinearGradientImplDefault(x0, y0, x1, y1, self.getCanvasElement()) - - + + """* * * Creates a RadialGradient Object for use as a fill or stroke style. @@ -159,8 +159,8 @@ def createLinearGradient(self, x0, y0, x1, y1): def createRadialGradient(self, x0, y0, r0, x1, y1, r1): return RadialGradientImplDefault(x0, y0, r0, x1, y1, r1, self.getCanvasElement()) - - + + """* * * Does nothing if the context's path is empty. Otherwise, it connects the @@ -181,8 +181,8 @@ def createRadialGradient(self, x0, y0, r0, x1, y1, r1): """ def cubicCurveTo(self, cp1x, cp1y, cp2x, cp2y, x, y): self.impl.cubicCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) - - + + """* * Draws an input image at a given position on the canvas. Resizes image * according to specified width and height and samples from the specified @@ -204,7 +204,7 @@ def cubicCurveTo(self, cp1x, cp1y, cp2x, cp2y, x, y): * @param offsetY y coord of the top left corner in the destination space * @param width the size of the image in the destination space * @param height the size of the image in the destination space - + option 3: * @param img the image to be drawn * @param sourceX the start X position in the source image @@ -239,15 +239,15 @@ def drawImage(self, img, *args): destX, destY, destWidth, destHeight) elif len(args) == 2: self.impl.drawImage(img, args[0], args[1]) - - + + """* * Fills the current path according to the current fillstyle. """ def fill(self): self.impl.fill() - - + + """* * Fills a rectangle of the specified dimensions, at the specified start * coords, according to the current fillstyle. @@ -259,7 +259,7 @@ def fill(self): """ def fillRect(self, startX, startY, width, height): self.impl.fillRect(startX, startY, width, height) - + """* * Places text, at the specified start * coords, according to the current fillstyle. @@ -270,8 +270,8 @@ def fillRect(self, startX, startY, width, height): """ def fillText(self, text, startX, startY, maxWidth=None): self.impl.fillText(text, startX, startY, maxWidth) - - + + """* * Returns the height in pixels of the canvas. * @@ -279,8 +279,8 @@ def fillText(self, text, startX, startY, maxWidth=None): """ def getCoordHeight(self): return self.coordHeight - - + + """* * * Returns the width in pixels of the canvas. @@ -289,8 +289,8 @@ def getCoordHeight(self): """ def getCoordWidth(self): return self.coordWidth - - + + """* * See self.setter method for a fully detailed description. * @@ -299,8 +299,8 @@ def getCoordWidth(self): """ def getGlobalAlpha(self): return self.impl.getGlobalAlpha() - - + + """* * See self.setter method for a fully detailed description. * @@ -309,8 +309,8 @@ def getGlobalAlpha(self): """ def getGlobalCompositeOperation(self): return self.impl.getGlobalCompositeOperation() - - + + """* * See self.setter method for a fully detailed description. * @@ -319,8 +319,8 @@ def getGlobalCompositeOperation(self): """ def getLineCap(self): return self.impl.getLineCap() - - + + """* * See self.setter method for a fully detailed description. * @@ -329,8 +329,8 @@ def getLineCap(self): """ def getLineJoin(self): return self.impl.getLineJoin() - - + + """* * See self.setter method for a fully detailed description. * @@ -339,8 +339,8 @@ def getLineJoin(self): """ def getLineWidth(self): return self.impl.getLineWidth() - - + + """* * See self.setter method for a fully detailed description. * @@ -349,8 +349,8 @@ def getLineWidth(self): """ def getMiterLimit(self): return self.impl.getMiterLimit() - - + + """* * Adds a line from the last point in the current path to the point defined by * x and y. @@ -360,8 +360,8 @@ def getMiterLimit(self): """ def lineTo(self, x, y): self.impl.lineTo(x, y) - - + + """* * Makes the last point in the current path be <b>(x,y)</b>. * @@ -370,8 +370,8 @@ def lineTo(self, x, y): """ def moveTo(self, x, y): self.impl.moveTo(x, y) - - + + """* * Does nothing if the context has an empty path. Otherwise it connects the * last point in the path to the given point <b>(x, y)</b> using a quadratic @@ -385,8 +385,8 @@ def moveTo(self, x, y): """ def quadraticCurveTo(self, cpx, cpy, x, y): self.impl.quadraticCurveTo(cpx, cpy, x, y) - - + + """* * Adds a rectangle to the current path, and closes the path. * @@ -397,8 +397,8 @@ def quadraticCurveTo(self, cpx, cpy, x, y): """ def rect(self, startX, startY, width, height): self.impl.rect(startX, startY, width, height) - - + + """* * Convenience function for resizing the canvas with consistent coordinate and * screen pixel spaces. Equivalent to doing: @@ -416,15 +416,15 @@ def resize(self, width, height): self.setCoordSize(width, height) self.setPixelHeight(height) self.setPixelWidth(width) - - + + """* * Restores the last saved context from the context stack. """ def restoreContext(self): self.impl.restoreContext() - - + + """* * Adds a rotation of the specified angle to the current transform. * @@ -432,15 +432,15 @@ def restoreContext(self): """ def rotate(self, angle): self.impl.rotate(angle) - - + + """* * Saves the current context to the context stack. """ def saveContext(self): self.impl.saveContext() - - + + """* * Adds a scale transformation to the current transformation matrix. * @@ -449,8 +449,8 @@ def saveContext(self): """ def scale(self, x, y): self.impl.scale(x, y) - - + + """* * Sets the background color of the canvas element. * @@ -458,8 +458,8 @@ def scale(self, x, y): """ def setBackgroundColor(self, color): self.impl.setBackgroundColor(self.getCanvasElement(), str(color)) - - + + """* * Sets the coordinate height of the Canvas. * <p> @@ -471,8 +471,8 @@ def setBackgroundColor(self, color): def setCoordHeight(self, height): self.impl.setCoordHeight(self.getCanvasElement(), height) self.coordHeight = height - - + + """* * Sets the coordinate space of the Canvas. * <p> @@ -485,8 +485,8 @@ def setCoordHeight(self, height): def setCoordSize(self, width, height): self.setCoordWidth(width) self.setCoordHeight(height) - - + + """* * Sets the coordinate width of the Canvas. * <p> @@ -498,8 +498,8 @@ def setCoordSize(self, width, height): def setCoordWidth(self, width): self.impl.setCoordWidth(self.getCanvasElement(), width) self.coordWidth = width - - + + """* * Set the current Fill Style to the specified color gradient. * @@ -507,8 +507,8 @@ def setCoordWidth(self, width): """ def setFillStyle(self, grad): self.impl.setFillStyle(grad) - - + + """* * Set the global transparency to the specified alpha. * @@ -516,7 +516,7 @@ def setFillStyle(self, grad): """ def setGlobalAlpha(self, alpha): self.impl.setGlobalAlpha(alpha) - + """* * Set the canvas font attribute. * @@ -543,8 +543,8 @@ def setFont(self, font): """ def setGlobalCompositeOperation(self, globalCompositeOperation): self.impl.setGlobalCompositeOperation(globalCompositeOperation) - - + + """* * A string value that determines the end style used when drawing a line. * Specify the string <code>GWTCanvas.BUTT</code> for a flat edge that is @@ -557,8 +557,8 @@ def setGlobalCompositeOperation(self, globalCompositeOperation): """ def setLineCap(self, lineCap): self.impl.setLineCap(lineCap) - - + + """* * A string value that determines the join style between lines. Specify the * string <code>GWTCanvas.ROUND</code> for round joins, @@ -571,8 +571,8 @@ def setLineCap(self, lineCap): """ def setLineJoin(self, lineJoin): self.impl.setLineJoin(lineJoin) - - + + """* * Sets the current context's linewidth. Line width is the thickness of a * stroked line. @@ -581,8 +581,8 @@ def setLineJoin(self, lineJoin): """ def setLineWidth(self, width): self.impl.setLineWidth(width) - - + + """* * A double value with the miter limit. You use this property to specify * how the canvas draws the juncture between connected line segments. If the @@ -596,8 +596,8 @@ def setLineWidth(self, width): """ def setMiterLimit(self, miterLimit): self.impl.setMiterLimit(miterLimit) - - + + """* * Sets the CSS height of the canvas in pixels. * @@ -606,8 +606,8 @@ def setMiterLimit(self, miterLimit): def setPixelHeight(self, height): FocusWidget.setHeight(self, str(height) + "px") self.impl.setPixelHeight(self.getCanvasElement(), height) - - + + """* * Sets the CSS width in pixels for the canvas. * @@ -616,8 +616,8 @@ def setPixelHeight(self, height): def setPixelWidth(self, width): FocusWidget.setWidth(self, str(width) + "px") self.impl.setPixelWidth(self.getCanvasElement(), width) - - + + """* * Set the current Stroke Style to the specified color gradient. * @@ -625,15 +625,15 @@ def setPixelWidth(self, width): """ def setStrokeStyle(self, grad): self.impl.setStrokeStyle(grad) - - + + """* * Strokes the current path according to the current stroke style. """ def stroke(self): self.impl.stroke() - - + + """* * Strokes a rectangle defined by the supplied arguments. * @@ -644,8 +644,8 @@ def stroke(self): """ def strokeRect(self, startX, startY, width, height): self.impl.strokeRect(startX, startY, width, height) - - + + """* * <code>The transform(m11, m12, m21, m22, dx, dy)</code> method must multiply * the current transformation matrix with the input matrix. Input described @@ -666,8 +666,8 @@ def strokeRect(self, startX, startY, width, height): """ def transform(self, m11, m12, m21, m22, dx, dy): self.impl.transform(m11, m12, m21, m22, dx, dy) - - + + """* * Applies a translation (linear shift) by x in the horizontal and by y in the * vertical. @@ -677,6 +677,6 @@ def transform(self, m11, m12, m21, m22, dx, dy): """ def translate(self, x, y): self.impl.translate(x, y) - + diff --git a/library/pyjamas/Canvas/GWTCanvasImplDefault.hulahop.py b/library/pyjamas/Canvas/GWTCanvasImplDefault.hulahop.py index 0f04298b9..f3a49bac9 100644 --- a/library/pyjamas/Canvas/GWTCanvasImplDefault.hulahop.py +++ b/library/pyjamas/Canvas/GWTCanvasImplDefault.hulahop.py @@ -1,5 +1,5 @@ def cvt(s): - if isinstance(s, str): + if isinstance(s, str): return unicode(s) return s diff --git a/library/pyjamas/Canvas/GWTCanvasImplDefault.py b/library/pyjamas/Canvas/GWTCanvasImplDefault.py index 840a42cfc..482b35468 100644 --- a/library/pyjamas/Canvas/GWTCanvasImplDefault.py +++ b/library/pyjamas/Canvas/GWTCanvasImplDefault.py @@ -56,7 +56,7 @@ def cubicCurveTo(self, cp1x, cp1y, cp2x, cp2y, x, y): def setFont(self, font): self.canvasContext.font = font - + def fillText(self, text, sourceX, sourceY, maxWidth=None): # TODO: split this dog's dinner into browser-specific # and pyjd-specific overrides... diff --git a/library/pyjamas/Canvas/GWTCanvasImplIE6.mshtml.py b/library/pyjamas/Canvas/GWTCanvasImplIE6.mshtml.py index c2fb6e377..3c5175009 100644 --- a/library/pyjamas/Canvas/GWTCanvasImplIE6.mshtml.py +++ b/library/pyjamas/Canvas/GWTCanvasImplIE6.mshtml.py @@ -20,5 +20,5 @@ def addNamespace(): except: doc().namespaces.add("v", "urn:schemas-microsoft-com:vml") doc().createStyleSheet().cssText = "v\\:*{behavior:url(#default#VML);}" - + ns = doc().namespaces.item("v") diff --git a/library/pyjamas/Canvas/GWTCanvasImplIE6.py b/library/pyjamas/Canvas/GWTCanvasImplIE6.py index 06cdb510c..f3f5b3249 100644 --- a/library/pyjamas/Canvas/GWTCanvasImplIE6.py +++ b/library/pyjamas/Canvas/GWTCanvasImplIE6.py @@ -25,9 +25,9 @@ from pyjamas.Canvas.GWTCanvasImplIEConsts import BUTT, DESTINATION_OVER, SOURCE_OVER -from pyjamas.Canvas import GWTCanvasConsts -from pyjamas.Canvas.JSOStack import JSOStack -from pyjamas.Canvas import PathElement +from pyjamas.Canvas import GWTCanvasConsts +from pyjamas.Canvas.JSOStack import JSOStack +from pyjamas.Canvas import PathElement from pyjamas.Canvas.VMLContext import VMLContext from pyjamas.Canvas.VMLContext import VMLStyle from pyjamas.Canvas.Color import Color @@ -54,7 +54,7 @@ def __init__(self): except: doc().namespaces.add("v", "urn:schemas-microsoft-com:vml") doc().createStyleSheet().cssText = "v\\:*{behavior:url(#default#VML);}" - + """* @@ -155,7 +155,7 @@ def drawImage(self, img, *args): destY = args[1] destWidth = fullWidth destHeight = fullHeight - + vmlStr = [] # JSOStack.getScratchArray() vmlStr.append("<v:group style=\"position:absolute;width:10;height:10;") @@ -273,7 +273,7 @@ def appendGradient(self, style, shapeStr): # need some proper math to calculate the focus position focusX = 50 focusY = 50 - + # Now add all the color stops colors = "" for i in range(1, len(colorStops)): @@ -562,7 +562,7 @@ def setFillStyle(self, fillStyle): if isinstance(fillStyle, CanvasGradientImplIE6): self.context.fillStyle.type = 'Gradient' self.context.fillStyle.gradient = fillStyle - #Window.alert("gradient fillstyle: " + + #Window.alert("gradient fillstyle: " + # str(len(self.context.fillStyle.gradient.colorStops))) else: fillStyle = str(fillStyle).strip() diff --git a/library/pyjamas/Canvas/GradientFactoryImplDefault.py b/library/pyjamas/Canvas/GradientFactoryImplDefault.py index 267e8d21a..aea51c2f1 100644 --- a/library/pyjamas/Canvas/GradientFactoryImplDefault.py +++ b/library/pyjamas/Canvas/GradientFactoryImplDefault.py @@ -25,6 +25,6 @@ """ def createLinearGradient(x0, y0, x1, y1, c): return LinearGradientImplDefault(x0,y0,x1,y1,c) - + def createRadialGradient(x0, y0, r0, x1, y1, r1, c): return RadialGradientImplDefault(x0,y0,r0,x1,y1,r1,c) diff --git a/library/pyjamas/Canvas/HTML5Canvas.ie6.py b/library/pyjamas/Canvas/HTML5Canvas.ie6.py index 723fb626d..52a2a59a9 100644 --- a/library/pyjamas/Canvas/HTML5Canvas.ie6.py +++ b/library/pyjamas/Canvas/HTML5Canvas.ie6.py @@ -1,5 +1,5 @@ class HTML5Canvas(Widget): - + def getCanvasImpl(self): return HTML5CanvasImplIE6() def createLinearGradient(self, x0, y0, x1, y1): diff --git a/library/pyjamas/Canvas/HTML5Canvas.py b/library/pyjamas/Canvas/HTML5Canvas.py index 48bc280bf..5f4301cc6 100644 --- a/library/pyjamas/Canvas/HTML5Canvas.py +++ b/library/pyjamas/Canvas/HTML5Canvas.py @@ -17,37 +17,37 @@ Note that this API is incompatible with Internet Explorer older than version 9. """ class HTML5Canvas(GWTCanvas): - - + + def getCanvasImpl(self): return HTML5CanvasImplDefault() - + def clearRect(self, x, y, w, h): self.impl.clearRect(x, y, w, h) - + """ clips the current path """ def clip(self): self.impl.clip() - + """ - Returns an ImageData object with the given dimensions in CSS pixels (which - might map to a different number of actual device pixels exposed by the + Returns an ImageData object with the given dimensions in CSS pixels (which + might map to a different number of actual device pixels exposed by the object itself). All the pixels in the returned object are transparent black. """ def createImageData(self, sw, sh): return ImageData(self.impl.createImageData(sw, sh)) - + """ - Returns an ImageData object containing the image data for the given + Returns an ImageData object containing the image data for the given rectangle of the canvas. """ def getImageData(self, sx, sy, sw, sh): return ImageData(self.impl.getImageData(sx, sy, sw, sh)) - + """ - Paints the data from the given ImageData object onto the canvas. If a dirty + Paints the data from the given ImageData object onto the canvas. If a dirty rectangle is provided, only the pixels from that rectangle are painted. """ def putImageData(self, imagedata, dx, dy, dirtyX=0, dirtyY=0, dirtyWidth=None, dirtyHeight=None): @@ -56,86 +56,86 @@ def putImageData(self, imagedata, dx, dy, dirtyX=0, dirtyY=0, dirtyWidth=None, d if dirtyHeight == None: dirtyHeight = self.coordHeight self.impl.putImageData(imagedata, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight) - + """ - returns the canvas data as a base64 encoded PNG file, also supports + returns the canvas data as a base64 encoded PNG file, also supports image/jpg in Firefox """ def toDataURL(self, type="image/png"): return self.impl.toDataURL(type) - + """ Returns a string corresponding to current font size and type, for example: "10px monospace" """ def getFont(self): return self.impl.getFont() - + """ - returns the width in pixels the passed in string would take up when drawn + returns the width in pixels the passed in string would take up when drawn with currently set font size and type """ def measureText(self, text): return self.impl.measureText(text) - + """ - Sets current font to passed in size and type, if the string is in invalid + Sets current font to passed in size and type, if the string is in invalid format, the font will not be updated """ def setFont(self, value): self.impl.setFont(value) - + """ returns the current level of blur applied to shadows """ def getShadowBlur(self): return self.impl.getShadowBlur() - + """ returns the current shadow color """ def getShadowColor(self): return Color(self.impl.getShadowColor()) - + """ returns the current horizontal shadow offset """ def getShadowOffsetX(self): self.impl.getShadowOffsetX() - + """ Returns the current text alignment settings """ def getTextAlign(self): return self.impl.getTextAlign() - + """ returns the current vertical shadow offset """ def getShadowOffsetY(self): self.impl.getShadowOffsetY() - + """ - sets blur level of shadows, values that are not finite numbers greater + sets blur level of shadows, values that are not finite numbers greater than or equal to zero are ignored """ def setShadowBlur(self, blur): self.impl.setShadowBlur(blur) - + """ sets the current shadow color """ def setShadowColor(self, color): self.impl.setShadowColor(str(color)) - + """ sets the current shadow offset """ def setShadowOffset(self, x, y): self.impl.setShadowOffset(x, y) - + """ - Sets the current text alignment settings. The possible values are start, + Sets the current text alignment settings. The possible values are start, end, left, right, and center """ def setTextAlign(self, loc): diff --git a/library/pyjamas/Canvas/HTML5CanvasImplDefault.py b/library/pyjamas/Canvas/HTML5CanvasImplDefault.py index f9097393b..8d91e77cd 100644 --- a/library/pyjamas/Canvas/HTML5CanvasImplDefault.py +++ b/library/pyjamas/Canvas/HTML5CanvasImplDefault.py @@ -9,58 +9,58 @@ class HTML5CanvasImplDefault(GWTCanvasImplDefault): - + def clearRect(self, x, y, w, h): self.canvasContext.clearRect(x, y, w, h) - + def clip(self): self.canvasContext.clip() - + def createImageData(self, sw, sh): return self.canvasContext.createImageData(sw, sh) - + def getFont(self): return self.canvasContext.font - + def getImageData(self, sx, sy, sw, sh): return self.canvasContext.getImageData(sx, sy, sw, sh) - + def getShadowBlur(self): return self.canvasContext.shadowBlur - + def getShadowColor(self): return self.canvasContext.shadowColor - + def getShadowOffsetX(self): return self.canvasContext.shadowOffsetX - + def getShadowOffsetY(self): return self.canvasContext.shadowOffsetY - + def getTextAlign(self): return self.impl.textAlign - + def measureText(self, text): return self.canvasContext.measureText(text).width - + def putImageData(self, imagedata, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight): self.canvasContext.putImageData(imagedata, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight) - + def setFont(self, value): self.canvasContext.font = value - + def setShadowBlur(self, blur): self.canvasContext.shadowBlur = blur - + def setShadowColor(self, color): self.canvasContext.shadowColor = color - + def setShadowOffset(self, x, y): self.canvasContext.shadowOffsetX = x self.canvasContext.shadowOffsetY = y - + def setTextAlign(self, loc): self.impl.textAlign = loc - + def toDataURL(self, type): return self.canvasContext.toDataURL(type) diff --git a/library/pyjamas/Canvas/HTML5CanvasImplIE6.py b/library/pyjamas/Canvas/HTML5CanvasImplIE6.py index e6fc94da4..13f557d19 100644 --- a/library/pyjamas/Canvas/HTML5CanvasImplIE6.py +++ b/library/pyjamas/Canvas/HTML5CanvasImplIE6.py @@ -9,62 +9,62 @@ """ -This is a dummy class for Internet Explorer browsers older than version 9. It +This is a dummy class for Internet Explorer browsers older than version 9. It doesn't implement the additional HTML5 Canvas functionality, simply allows IE to fail in a way that gives feedback back to the user/developer. """ class HTML5CanvasImplIE6(GWTCanvasImplIE6): - + def clearRect(self, x, y, w, h): raise NotImplementedError - + def clip(self): raise NotImplementedError - + def createImageData(self, sw, sh): raise NotImplementedError - + def getFont(self): raise NotImplementedError - + def getImageData(self, sx, sy, sw, sh): raise NotImplementedError - + def getShadowBlur(self): raise NotImplementedError - + def getShadowColor(self): raise NotImplementedError - + def getShadowOffsetX(self): raise NotImplementedError - + def getShadowOffsetY(self): raise NotImplementedError - + def getTextAlign(self): raise NotImplementedError - + def measureText(self, text): raise NotImplementedError - + def putImageData(self, imagedata, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight): raise NotImplementedError - + def setFont(self, value): raise NotImplementedError - + def setShadowBlur(self, blur): raise NotImplementedError - + def setShadowColor(self, color): raise NotImplementedError - + def setShadowOffset(self, x, y): raise NotImplementedError - + def setTextAlign(self, loc): raise NotImplementedError - + def toDataURL(self, type): raise NotImplementedError diff --git a/library/pyjamas/Canvas/ImageData.py b/library/pyjamas/Canvas/ImageData.py index 59928f6ab..8451ce0df 100644 --- a/library/pyjamas/Canvas/ImageData.py +++ b/library/pyjamas/Canvas/ImageData.py @@ -6,7 +6,7 @@ """ """ -This class wraps around ImageData HTML5 Canvas object and allows easier +This class wraps around ImageData HTML5 Canvas object and allows easier per-pixel access """ class ImageData: @@ -14,23 +14,23 @@ def __init__(self, imagedata): self.width = imagedata.width self.height = imagedata.height self.data = imagedata.data - + def getWidth(self): return self.width - + def getHeight(self): return self.height - + def getData(self): return self.data - + def setData(self, data): self.data = data - + def getPixel(self, x, y): offset = (y*self.width + x)*4 return self.data[offset:offset+4] - + """ rgba must be an array of 4 integers ranging from 0 to 255 """ diff --git a/library/pyjamas/Canvas/ImageLoader.py b/library/pyjamas/Canvas/ImageLoader.py index 42ead113e..24ec42940 100644 --- a/library/pyjamas/Canvas/ImageLoader.py +++ b/library/pyjamas/Canvas/ImageLoader.py @@ -30,16 +30,16 @@ * method once all specified Images are loaded. """ class ImageLoader: - - + + def __init__(self): - + self.images = [] self.callBack = None self.loadedImages = 0 self.totalImages = 0 - - + + """* * Stores the ImageElement reference so that when all the images report * an onload, we can return the array of all the ImageElements. @@ -48,8 +48,8 @@ def __init__(self): def addHandle(self, img): self.totalImages += 1 self.images.append(img) - - + + """* * Invokes the onImagesLoaded method in the CallBack if all the * images are loaded AND we have a CallBack specified. @@ -61,9 +61,9 @@ def dispatchIfComplete(self): self.callBack.onImagesLoaded(self.images) # remove the image loader imageLoaders.remove(self) - - - + + + """* * Sets the callback object for the ImageLoader. * Once this is set, we may invoke the callback once all images that @@ -73,16 +73,16 @@ def dispatchIfComplete(self): """ def finalize(self, cb): self.callBack = cb - - + + def incrementLoadedImages(self): self.loadedImages += 1 - - + + def isAllLoaded(self): return (self.loadedImages == self.totalImages) - - + + """* * Returns a handle to an img object. Ties back to the ImageLoader instance """ @@ -97,24 +97,24 @@ def prepareImage(self, url): DOM.setEventListener(img.getElement(), img) DOM.sinkEvents(img.getElement(), Event.ONLOAD) return img - + def onLoad(self, img): if not img.__isLoaded: - + # __isLoaded should be set for the first time here. # if for some reason img fires a second onload event # we do not want to execute the following again (hence the guard) img.__isLoaded = True; self.incrementLoadedImages(); img.removeLoadListener(self) - + # we call this function each time onload fires # It will see if we are ready to invoke the callback self.dispatchIfComplete(); - + return img; - + """* @@ -131,11 +131,11 @@ def loadImages(urls, cb): il = ImageLoader() for i in range(len(urls)): il.addHandle(il.prepareImage(urls[i])) - + il.finalize(cb) imageLoaders.append(il) # Go ahead and fetch the images now for i in range(len(urls)): il.images[i].setUrl(urls[i]) - + diff --git a/library/pyjamas/Canvas/ImageLoaderhulahop.py b/library/pyjamas/Canvas/ImageLoaderhulahop.py index 824176146..beff499af 100644 --- a/library/pyjamas/Canvas/ImageLoaderhulahop.py +++ b/library/pyjamas/Canvas/ImageLoaderhulahop.py @@ -30,16 +30,16 @@ * method once all specified Images are loaded. """ class ImageLoader: - - + + def __init__(self): - + self.images = [] self.callBack = None self.loadedImages = 0 self.totalImages = 0 - - + + """* * Stores the ImageElement reference so that when all the images report * an onload, we can return the array of all the ImageElements. @@ -48,8 +48,8 @@ def __init__(self): def addHandle(self, img): self.totalImages += 1 self.images.append(img) - - + + """* * Invokes the onImagesLoaded method in the CallBack if all the * images are loaded AND we have a CallBack specified. @@ -61,9 +61,9 @@ def dispatchIfComplete(self): self.callBack.onImagesLoaded(self.images) # remove the image loader imageLoaders.remove(self) - - - + + + """* * Sets the callback object for the ImageLoader. * Once this is set, we may invoke the callback once all images that @@ -73,16 +73,16 @@ def dispatchIfComplete(self): """ def finalize(self, cb): self.callBack = cb - - + + def incrementLoadedImages(self): self.loadedImages += 1 - - + + def isAllLoaded(self): return (self.loadedImages == self.totalImages) - - + + def _onload(self, form, event, something): if not self.__formAction: return @@ -120,19 +120,19 @@ def prepareImage(self, url): JS(""" // if( callback specified ) // do nothing - + var __this = this; - + @{{img}}.onload = function() { if(!@{{img}}.__isLoaded) { - + // __isLoaded should be set for the first time here. // if for some reason img fires a second onload event // we do not want to execute the following again (hence the guard) @{{img}}.__isLoaded = true; __this.incrementLoadedImages(); @{{img}}.onload = null; - + // we call this function each time onload fires // It will see if we are ready to invoke the callback __this.dispatchIfComplete(); @@ -141,10 +141,10 @@ def prepareImage(self, url): __this.dispatchIfComplete(); } } - + return @{{img}}; """) - + def init(): diff --git a/library/pyjamas/Canvas/JSOStack.mshtml.py b/library/pyjamas/Canvas/JSOStack.mshtml.py index fbd913aae..37a8dfbee 100644 --- a/library/pyjamas/Canvas/JSOStack.mshtml.py +++ b/library/pyjamas/Canvas/JSOStack.mshtml.py @@ -18,7 +18,7 @@ class JSOStack: - + def __init__(self): self.clear() diff --git a/library/pyjamas/Canvas/JSOStack.py b/library/pyjamas/Canvas/JSOStack.py index fbd913aae..37a8dfbee 100644 --- a/library/pyjamas/Canvas/JSOStack.py +++ b/library/pyjamas/Canvas/JSOStack.py @@ -18,7 +18,7 @@ class JSOStack: - + def __init__(self): self.clear() diff --git a/library/pyjamas/Canvas/LinearGradientImplDefault.py b/library/pyjamas/Canvas/LinearGradientImplDefault.py index 9421a6e14..e156a918a 100644 --- a/library/pyjamas/Canvas/LinearGradientImplDefault.py +++ b/library/pyjamas/Canvas/LinearGradientImplDefault.py @@ -15,7 +15,7 @@ """ -from pyjamas.Canvas.CanvasGradientImplDefault import CanvasGradientImplDefault +from pyjamas.Canvas.CanvasGradientImplDefault import CanvasGradientImplDefault """* * Default deferred binding of GradientFactory will create instances of this class. @@ -26,7 +26,7 @@ class LinearGradientImplDefault(CanvasGradientImplDefault): def __init__(self, x0, y0, x1, y1, c): CanvasGradientImplDefault.__init__(self) self.createNativeGradientObject(x0,y0,x1,y1,c) - + def createNativeGradientObject(self, x0, y0, x1, y1, c): ctx = c.getContext('2d') diff --git a/library/pyjamas/Canvas/PathElement.py b/library/pyjamas/Canvas/PathElement.py index ce1f69412..bf4b4b90c 100644 --- a/library/pyjamas/Canvas/PathElement.py +++ b/library/pyjamas/Canvas/PathElement.py @@ -31,17 +31,17 @@ CUBIC = " c" def arc(x, y, radius, startAngle, endAngle, antiClockwise, canvas): - + matrix = canvas.matrix context = canvas.context - + if not antiClockwise: realStartAngle = endAngle realEndAngle = startAngle else: realStartAngle = startAngle realEndAngle = endAngle - + ar = radius * 10 startX = (x + math.cos(realStartAngle) * ar - 5) startY = (y + math.sin(realStartAngle) * ar - 5) @@ -49,8 +49,8 @@ def arc(x, y, radius, startAngle, endAngle, antiClockwise, canvas): endY = (y + math.sin(realEndAngle) * ar - 5) if startX == endX and not antiClockwise: startX += 0.125 - - + + cx = canvas.getCoordX(matrix, x, y) cy = canvas.getCoordY(matrix, x, y) arcX = (context.arcScaleX * ar) diff --git a/library/pyjamas/Canvas/RadialGradientImplDefault.py b/library/pyjamas/Canvas/RadialGradientImplDefault.py index 6b1b013bc..11b54c17f 100644 --- a/library/pyjamas/Canvas/RadialGradientImplDefault.py +++ b/library/pyjamas/Canvas/RadialGradientImplDefault.py @@ -14,7 +14,7 @@ * the License. """ -from pyjamas.Canvas.CanvasGradientImplDefault import CanvasGradientImplDefault +from pyjamas.Canvas.CanvasGradientImplDefault import CanvasGradientImplDefault """* @@ -22,14 +22,14 @@ * for RadialGradients. """ class RadialGradientImplDefault(CanvasGradientImplDefault): - + def __init__(self, x0, y0, r0, x1, y1, r1, c): CanvasGradientImplDefault.__init__(self) self.createNativeGradientObject(x0,y0,r0,x1,y1,r1, c) - + def createNativeGradientObject(self, x0, y0, r0, x1, y1, r1, c): ctx = c.getContext('2d') gradient = ctx.createRadialGradient(x0,y0,r0,x1,y1,r1) self.setNativeGradient(gradient) - + diff --git a/library/pyjamas/Canvas/RadialGradientImplIE6.py b/library/pyjamas/Canvas/RadialGradientImplIE6.py index d0d206976..f01d90875 100644 --- a/library/pyjamas/Canvas/RadialGradientImplIE6.py +++ b/library/pyjamas/Canvas/RadialGradientImplIE6.py @@ -14,21 +14,21 @@ * the License. """ -from pyjamas.Canvas.CanvasGradientImplIE6 import CanvasGradientImplIE6 +from pyjamas.Canvas.CanvasGradientImplIE6 import CanvasGradientImplIE6 """* * IE6 deferred binding of Gradient Factory will create instances of this class * for RadialGradients. """ class RadialGradientImplIE6 (CanvasGradientImplIE6): - + def __init__(self, x0, y0, r0, x1, y1, r1): CanvasGradientImplIE6.__init__(self, x0,y0,x1,y1) self.startRad = r0 self.endRad = r1 self.type = "gradientradial" - - + + def cloneGradient(self): newGrad = RadialGradientImplIE6(self.startX,self.startY, self.startRad, @@ -40,14 +40,14 @@ def cloneGradient(self): newGrad.endX = self.endX newGrad.endY = self.endY newGrad.endRad = self.endRad - + cStops = self.colorStops - + for i in range(len(cStops)): newGrad.colorStops.append(cStops[i].cloneColorStop()) - + return newGrad - - + + diff --git a/library/pyjamas/Canvas/SVGCanvas.py b/library/pyjamas/Canvas/SVGCanvas.py index 0544064d9..be4c849f8 100644 --- a/library/pyjamas/Canvas/SVGCanvas.py +++ b/library/pyjamas/Canvas/SVGCanvas.py @@ -37,7 +37,7 @@ ROUND = "round" BEVEL = "bevel" - + """ SVGCanvas gradient implementation. """ @@ -68,17 +68,17 @@ def _get_svg_coord_percent(self, coordXY): newY = int((coordXY[1]/self.canvas_height) * 100.0) # return result return (newX, newY) - + # add a color stop element as a child def addColorStop(self, offset, color): # create a color stop element stop = self._createElementSVG("stop") - stop.setAttributeNS(None, "stop-color", color); + stop.setAttributeNS(None, "stop-color", color); # offset is specified as a float, but it should be percent offset = int(offset*100) # and it's a string offset = str(offset)+"%" - stop.setAttributeNS(None, "offset", offset); + stop.setAttributeNS(None, "offset", offset); # now add the color stop as child DOM.appendChild(self.elem, stop) @@ -132,7 +132,7 @@ def addColorStop(self, offset, color): P = (offset*(self.radii[1] - self.radii[0]) + self.radii[0]) / self.radii[1] # pass to base to be converted to percent and added in SVGCanvasGradient.addColorStop(self, P, color) - + """ SVG-based canvas to mimic the capabilities available in the 2D Canvas. @@ -143,12 +143,12 @@ def addColorStop(self, offset, color): canvas size limits of the 2D Canvas implementation of Windows Firefox """ class SVGCanvas(FocusWidget): - + def __init__(self, coordX=None, coordY=None, pixelX=None, pixelY=None, **kwargs): """ Creates an SVGCanvas element. Element type is 'svg' - + @param coordX the size of the coordinate space in the x direction @param coordY the size of the coordinate space in the y direction @param pixelX the CSS width in pixels of the canvas element @@ -222,7 +222,7 @@ def _init_context(self): "transform_group":self.canvas, # current transformation values "matrix":[1,0,0,1,0,0]} - + # just integerize a pair of coordinates def _integerize(self, x,y): # we use int coords only @@ -240,7 +240,7 @@ def _setPoint(self, x, y): self.first_point = self.last_point # return result return self.last_point - + def getCanvasElement(self): return self.canvas @@ -249,7 +249,7 @@ def getCanvasElement(self): ## Canvas drawing methods ## ################################### - + def beginPath(self): """ Erases the current path and prepares it for a path. @@ -262,7 +262,7 @@ def beginPath(self): def moveTo(self, x, y): """ Makes the last point in the current path be <b>(x,y)</b>. - + @param x x coord of point @param y y coord of point """ @@ -270,13 +270,13 @@ def moveTo(self, x, y): self._setPoint(x,y) # add move to current path self.path_string += "M "+str(self.last_point[0])+" "+str(self.last_point[1])+" " - - + + def lineTo(self, x, y): """* Adds a line from the last point in the current path to the point defined by x and y. - + @param x x coord of point @param y y coord of point """ @@ -286,8 +286,8 @@ def lineTo(self, x, y): if self.first_point is None: self.first_point = self.last_point self.path_string += "L "+str(self.last_point[0])+" "+str(self.last_point[1])+" " - - + + def clear(self): """ Clears the entire canvas. @@ -305,18 +305,18 @@ def clear(self): # self._init_context() # also reset path self.beginPath() - + def cubicCurveTo(self, cp1x, cp1y, cp2x, cp2y, x, y): """ Does nothing if the context's path is empty. Otherwise, it connects the last point in the path to the given point <b>(x, y)</b> using a cubic Bezier curve with control points <b>(cp1x, cp1y)</b> and <b>(cp2x, cp2y)</b>. Then, it must add the point <b>(x, y)</b> to the path. - + This function corresponds to the <code>bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)</code> method in canvas element Javascript API. - + @param cp1x x coord of first Control Point @param cp1y y coord of first Control Point @param cp2x x coord of second Control Point @@ -340,7 +340,7 @@ def quadraticCurveTo(self, cpx, cpy, x, y): last point in the path to the given point <b>(x, y)</b> using a quadratic Bezier curve with control point <b>(cpx, cpy)</b>, and then adds the given point <b>(x, y)</b> to the path. - + @param cpx x coord of the control point @param cpy y coord of the control point @param x x coord of the point @@ -365,7 +365,7 @@ def closePath(self): self.path_string += "Z " # and close the points self.last_point = self.first_point - + def fill(self): """ @@ -407,7 +407,7 @@ def _apply_stroke_styles(self, elem): # add the current stroke opacity attribute if self.ctx["alpha"] < 1.0: DOM.setElemAttribute(elem, "stroke-opacity", str(self.ctx["alpha"])) - + def stroke(self): """ Strokes the current path according to the current stroke style. @@ -439,7 +439,7 @@ def _posAngle(self, angle): def arc(self, centerX, centerY, radius, startAngle, endAngle, antiClockwise): """ Draws an arc (circle segment). - + @param x center X coordinate @param y center Y coordinate @param radius radius of drawn arc @@ -504,7 +504,7 @@ def fillRect(self, startX, startY, width, height): """ Fills a rectangle of the specified dimensions, at the specified start coords, according to the current fillstyle. - + @param startX x coord of the top left corner in the destination space @param startY y coord of the top left corner in the destination space @param width destination width of image @@ -527,7 +527,7 @@ def fillRect(self, startX, startY, width, height): def strokeRect(self, startX, startY, width, height): """ Strokes a rectangle defined by the supplied arguments. - + @param startX x coord of the top left corner @param startY y coord of the top left corner @param width width of the rectangle @@ -547,7 +547,7 @@ def strokeRect(self, startX, startY, width, height): def rect(self, startX, startY, width, height): """* Adds an unfilled/stroked rectangle to the current path, and closes the path. - + @param startX x coord of the top left corner of the rectangle @param startY y coord of the top left corner of the rectangle @param width the width of the rectangle @@ -565,7 +565,7 @@ def fillText(self, text, startX, startY, maxWidth=None): """ Places text, at the specified start coords, according to the current fillstyle. - + @param startX x coord of the top left corner in the destination space @param startY y coord of the top left corner in the destination space @param maxWidth maximum width of text @@ -586,12 +586,12 @@ def fillText(self, text, startX, startY, maxWidth=None): DOM.setInnerText(text_elem, text) # add the rect element to the canvas self._addElementSVG(text_elem) - - + + def createLinearGradient(self, x0, y0, x1, y1): """ Creates a LinearGradient Object for use as a fill or stroke style. - + @param x0 x coord of start point of gradient @param y0 y coord of start point of gradient @param x1 x coord of end point of gradient @@ -602,12 +602,12 @@ def createLinearGradient(self, x0, y0, x1, y1): return SVGCanvasLinearGradient(self.defs, self.pixelWidth, self.pixelHeight, int(x0),int(y0), int(x1),int(y1)) - - + + def createRadialGradient(self, x0, y0, r0, x1, y1, r1): """ Creates a RadialGradient Object for use as a fill or stroke style. - + @param x0 x coord of origin of start circle @param y0 y coord of origin of start circle @param r0 radius of start circle @@ -621,16 +621,16 @@ def createRadialGradient(self, x0, y0, r0, x1, y1, r1): int(x0),int(y0),int(r0), int(x1),int(y1),int(r1)) - + def drawImage(self, img, *args): """ Draws an input image at a given position on the canvas. Resizes image according to specified width and height and samples from the specified sourceY and sourceX. - + We recommend that the pixel and coordinate spaces be the same to provide consistent positioning and scaling results - + option 1: @param img the image to be drawn @param destX x coord of the top left corner in the destination space @@ -642,7 +642,7 @@ def drawImage(self, img, *args): @param destY y coord of the top left corner in the destination space @param destWidth the width of drawn image in the destination @param destHeight the height of the drawn image in the destination - + option 3: @param img the image to be drawn @param sourceX the start X position in the source image @@ -697,7 +697,7 @@ def drawImage(self, img, *args): # print 'Create: <image xlink:href="'+url+'" x="'+str(destXY[0])+'" y="'+str(destXY[1])+'" height="'+str(destWH[1])+'px" width="'+str(destWH[0])+'px"/>' image = self._createElementSVG("image") # set the URL - image.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", url); + image.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", url); # set the pos/dimensions DOM.setElemAttribute(image, "x", str(int(destXY[0]))) DOM.setElemAttribute(image, "y", str(int(destXY[1]))) @@ -706,7 +706,7 @@ def drawImage(self, img, *args): # add the element to the canvas self._addElementSVG(image) - + def saveContext(self): """ Saves the current context to the context stack. @@ -715,7 +715,7 @@ def saveContext(self): self.ctx_stack.append(dict(self.ctx)) # print "SAVED:",self.ctx - + def restoreContext(self): """ Restores the last saved context from the context stack. @@ -728,17 +728,17 @@ def restoreContext(self): self.ctx = self.ctx_stack.pop() # print "RESTORED:",self.ctx - + ################################### ## ## Canvas drawing styles ## ################################### - + def getLineCap(self): """ See self.setter method for a fully detailed description. - + @return @see GWTCanvas#setLineCap(String) """ @@ -752,22 +752,22 @@ def setLineCap(self, lineCap): endpoints, or <code>GWTCanvas.SQUARE</code> for square endpoints. If you do not self.set this value explicitly, the canvas uses the <code>GWTCanvas.BUTT</code> line cap style. - + @param lineCap """ self.ctx["linecap"] = lineCap - + def getLineJoin(self): """ See self.setter method for a fully detailed description. - + @return @see GWTCanvas#setLineJoin(String) """ return self.ctx["linejoin"] - - + + def setLineJoin(self, lineJoin): """ A string value that determines the join style between lines. Specify the @@ -776,41 +776,41 @@ def setLineJoin(self, lineJoin): <code>GWTCanvas.MITER</code> for miter joins. If you do not self.set this value explicitly, the canvas uses the <code>GWTCanvas.MITER</code> line join style. - + @param lineJoin """ self.ctx["linejoin"] = lineJoin - - + + def getLineWidth(self): """ See self.setter method for a fully detailed description. - + @return @see GWTCanvas#setLineWidth(double) """ return self.ctx["stroke-width"] - - + + def setLineWidth(self, width): """ Sets the current context's linewidth. Line width is the thickness of a stroked line. - + @param width the width of the canvas """ self.ctx["stroke-width"] = int(width) - - + + def getMiterLimit(self): """ See self.setter method for a fully detailed description. - + @return @see GWTCanvas#setMiterLimit(double) """ return self.ctx["miterlimit"] - + def setMiterLimit(self, miterLimit): """ A double value with the miter limit. You use this property to specify @@ -820,16 +820,16 @@ def setMiterLimit(self, miterLimit): of a miter. The canvas divides the length of the miter by the line width. If the result is greater than the miter limit, the style is converted to a bevel. - + @param miterLimit """ self.ctx["miterlimit"] = miterLimit - + def setStrokeStyle(self, grad): """ Set the current Stroke Style to the specified color gradient. - + @param grad {@link CanvasGradient} """ # if this is an actual Gradient @@ -837,13 +837,13 @@ def setStrokeStyle(self, grad): # get the ref sting to use for the fill attribute value grad = grad.getColor() # now save the value - self.ctx["stroke"] = grad - + self.ctx["stroke"] = grad + def setBackgroundColor(self, color): """ Sets the background color of the canvas element. - + @param color the background color. """ # set style value @@ -851,32 +851,32 @@ def setBackgroundColor(self, color): # set the canvas background color with the style attribute DOM.setElemAttribute(self.canvas, "style", style) - + def getGlobalAlpha(self): """ See self.setter method for a fully detailed description. """ - return self.ctx["alpha"] - + return self.ctx["alpha"] + def setGlobalAlpha(self, alpha): """ Set the global transparency to the specified alpha. - + @param alpha alpha value """ self.ctx["alpha"] = alpha - - + + def getGlobalCompositeOperation(self): """ See self.setter method for a fully detailed description. - + @return @see GWTCanvas#setGlobalCompositeOperation(String) """ return self.ctx["composite"] - - + + def setGlobalCompositeOperation(self, globalCompositeOperation): """ Determines how the canvas is displayed relative to any background content. @@ -890,16 +890,16 @@ def setGlobalCompositeOperation(self, globalCompositeOperation): <li><code>GWTCanvas.DESTINATION_OVER</code> </ul> <p> - + @param globalCompositeOperation is False for SOURCE_OVER (default) and True for SOURCE_UNDER """ self.ctx["composite"] = globalCompositeOperation - - + + def setFillStyle(self, grad): """ Set the current Fill Style to the specified color/gradient. - + @param grad {@link CanvasGradient} """ # if this is an actual Gradient @@ -919,7 +919,7 @@ def setFont(self, font): ## Canvas Coordinate space ## ################################### - + def setWidth(self, width): self.setPixelWidth(width) @@ -930,78 +930,78 @@ def resize(self, width, height): """ Convenience function for resizing the canvas with consistent coordinate and screen pixel spaces. Equivalent to doing: - + <pre><code> canvas.setCoordSize(width, height) canvas.setPixelHeight(height) canvas.setPixelWidth(width) </code></pre> - + @param width @param height """ self.setCoordSize(width, height) self.setPixelHeight(height) self.setPixelWidth(width) - - + + def setCoordSize(self, width, height): """ Sets the coordinate space of the Canvas. - + @param width the size of the x component of the coordinate space @param height the size of the y component of the coordinate space """ self.setCoordWidth(width) self.setCoordHeight(height) - - + + def getCoordHeight(self): """ Returns the height in pixels of the canvas. - + @return returns the height in pixels of the canvas """ return self.coordHeight - - + + def setCoordHeight(self, height): """ Sets the coordinate height of the Canvas. <p> This will erase the canvas contents! </p> - + @param height the size of the y component of the coordinate space """ self.coordHeight = int(height) self._set_base_transform() - + def getCoordWidth(self): """ Returns the width in pixels of the canvas. - + @return returns the width in pixels of the canvas """ return self.coordWidth - + def setCoordWidth(self, width): """ Sets the coordinate width of the Canvas. <p> This will erase the canvas contents! </p> - + @param width the size of the x component of the coordinate space """ self.coordWidth = int(width) self._set_base_transform() - + def setPixelHeight(self, height): """ Sets the CSS height of the canvas in pixels. - + @param height the height of the canvas in pixels """ height = int(height) @@ -1014,23 +1014,23 @@ def setPixelHeight(self, height): def setPixelWidth(self, width): """ Sets the CSS width in pixels for the canvas. - + @param width width of the canvas in pixels """ width = int(width) self.pixelWidth = width FocusWidget.setWidth(self, width) - DOM.setElemAttribute(self.canvas, "width", str(width)) + DOM.setElemAttribute(self.canvas, "width", str(width)) self._set_base_transform() - - + + # internal routine to set the current scaling transform def _set_base_transform(self): # clear any content self.clear() # set viewBox DOM.setElemAttribute(self.canvas, "viewBox", "0 0 "+str(self.coordWidth)+" "+str(self.coordHeight)) - + ################################### ## ## Transformations @@ -1084,18 +1084,18 @@ def _apply_current_transforms(self): # we need to update the transform attribute of the current group # print "Apply transform:",transform DOM.setElemAttribute(self.ctx["transform_group"], "transform", transform) - + def transform(self, m11, m12, m21, m22, dx, dy): """ <code>The transform(m11, m12, m21, m22, dx, dy)</code> method must multiply the current transformation matrix with the input matrix. Input described by: - + m11 m21 dx m12 m22 dy 0 0 1 - + @param m11 top left cell of 2x2 rotation matrix @param m12 top right cell of 2x2 rotation matrix @param m21 bottom left cell of 2x2 rotation matrix @@ -1105,11 +1105,11 @@ def transform(self, m11, m12, m21, m22, dx, dy): """ # TODO: multiply the transform with the current transform print "transform NOT IMPLEMENTED YET" - + def rotate(self, angle): """ Adds a rotation of the specified angle to the current transform. - + @param angle the angle to rotate by, <b>in radians</b> """ # first get current transform (leave off last row 0,0,1) @@ -1123,11 +1123,11 @@ def rotate(self, angle): # apply the current transforms self._apply_current_transforms() - + def scale(self, x, y): """ Adds a scale transformation to the current transformation matrix. - + @param x ratio that we must scale in the X direction @param y ratio that we must scale in the Y direction """ @@ -1138,13 +1138,13 @@ def scale(self, x, y): self.ctx["matrix"] = self._matrix_mult(t,m) # apply the current transforms self._apply_current_transforms() - - + + def translate(self, x, y): """ Applies a translation (linear shift) by x in the horizontal and by y in the vertical. - + @param x amount to shift in the x direction @param y amount to shift in the y direction """ diff --git a/library/pyjamas/Canvas2D.browser.py b/library/pyjamas/Canvas2D.browser.py index ce65b352d..a8eb94004 100644 --- a/library/pyjamas/Canvas2D.browser.py +++ b/library/pyjamas/Canvas2D.browser.py @@ -10,7 +10,7 @@ def init(self): var el = this.canvas; if (typeof $wnd.G_vmlCanvasManager != "undefined") { var parent = el.parent; - + el = $wnd.G_vmlCanvasManager.fixElement_(el); el.getContext = function () { if (this.context_) { @@ -18,7 +18,7 @@ def init(self): } return this.context_ = new $wnd.CanvasRenderingContext2D(el); }; - + el.attachEvent("onpropertychange", function (e) { // we need to watch changes to width and height switch (e.propertyName) { @@ -30,7 +30,7 @@ def init(self): }); // if style.height is set - + var attrs = el.attributes; if (attrs.width && attrs.width.specified) { // TODO: use runtimeStyle and coordsize @@ -44,11 +44,11 @@ def init(self): } } var ctx = el.getContext("2d"); - + ctx._createPattern = ctx.createPattern; ctx.createPattern = function(img, rep) { // Next line breaks things for Chrome - //if (!(img instanceof Image)) img = img.getElement(); + //if (!(img instanceof Image)) img = img.getElement(); return this._createPattern(img, rep); } @@ -61,7 +61,7 @@ def init(self): else if (a.length==5) return this._drawImage(a[0], a[1], a[2], a[3], a[4]); return this._drawImage(a[0], a[1], a[2]); } - + this.context = ctx; """) diff --git a/library/pyjamas/Canvas2D.py b/library/pyjamas/Canvas2D.py index cf6195a45..f985e5e3f 100644 --- a/library/pyjamas/Canvas2D.py +++ b/library/pyjamas/Canvas2D.py @@ -28,14 +28,14 @@ def __init__(self, Width=0, Height=0, **kwargs): kwargs['Height'] = Height self.context = None - - focusable = Focus.createFocusable() + + focusable = Focus.createFocusable() self.canvas = DOM.createElement("canvas") DOM.appendChild(focusable, self.canvas) FocusWidget.__init__(self, focusable, **kwargs) - + self.init() - + self.context.fillStyle = "black" self.context.strokeStyle = "black" @@ -56,11 +56,11 @@ def isEmulation(self): def init(self): el = self.getElement().firstChild ctx = el.getContext("2d") - + """ ctx._createPattern = ctx.createPattern ctx.createPattern = function(img, rep) { - if (!(img instanceof Image)) img = img.getElement(); + if (!(img instanceof Image)) img = img.getElement(); return self._createPattern(img, rep) } @@ -79,7 +79,7 @@ class CanvasImage(Image): def __init__(self, url="", load_listener = None): Image.__init__(self, url) if load_listener: - self.addLoadListener(load_listener) + self.addLoadListener(load_listener) self.onAttach() def isLoaded(self): @@ -90,14 +90,14 @@ class ImageLoadListener: def __init__(self, listener = None): self.wait_list = [] self.loadListeners = [] - + if listener: - self.addLoadListener(listener) + self.addLoadListener(listener) def add(self, sender): self.wait_list.append(sender) sender.addLoadListener(self) - + def addLoadListener(self, listener): self.loadListeners.append(listener) @@ -109,10 +109,10 @@ def isLoaded(self): def onError(self, sender): for listener in self.loadListeners: listener.onError(sender) - + def onLoad(self, sender): self.wait_list.remove(sender) - + if self.isLoaded(): for listener in self.loadListeners: listener.onLoad(self) diff --git a/library/pyjamas/Cookies.browser.py b/library/pyjamas/Cookies.browser.py index 91369c41c..88c5f790a 100644 --- a/library/pyjamas/Cookies.browser.py +++ b/library/pyjamas/Cookies.browser.py @@ -1,6 +1,6 @@ def getCookie(cookie_name): JS(""" - var results = document.cookie.match ( '(^|;) ?' + + var results = document.cookie.match ( '(^|;) ?' + @{{cookie_name}} + '=([^;]*)(;|$)' ); if ( results ) @@ -17,7 +17,7 @@ def setCookie(name, value, expires, domain=None, path=None, secure=False): if (@{{isUndefined}}(@{{domain}})) @{{domain}} = null; if (@{{isUndefined}}(@{{path}})) @{{path}} = null; if (@{{isUndefined}}(@{{secure}})) @{{secure}} = false; - + var today = new Date(); var expiration = new Date(); if (!@{{expires}}) @{{expires}} = 0; diff --git a/library/pyjamas/Cookies.py b/library/pyjamas/Cookies.py index 428e3acdc..fb0f14b1a 100644 --- a/library/pyjamas/Cookies.py +++ b/library/pyjamas/Cookies.py @@ -20,7 +20,7 @@ def getCookie2(cookie_name): if cs: return cs.value return None - + # expires can be int or Date def setCookie(name, value, expires, domain=None, path=None, secure=False): cookiestr = doc().cookie diff --git a/library/pyjamas/DOM.browser.py b/library/pyjamas/DOM.browser.py index 22482636e..da47ce1c6 100644 --- a/library/pyjamas/DOM.browser.py +++ b/library/pyjamas/DOM.browser.py @@ -69,18 +69,18 @@ def init(): $wnd.addEventListener('keydown', dce, true); $wnd.addEventListener('keyup', dce, true); $wnd.addEventListener('keypress', dce, true); - + $wnd.__dispatchEvent = function(evt) { - + var listener, curElem = this; - + while (curElem && !(listener = curElem.__listener)) { curElem = curElem.parentNode; } if (curElem && curElem.nodeType != 1) { curElem = null; } - + if (listener) { @{{dispatchEvent}}(evt, curElem, listener); } @@ -224,7 +224,7 @@ def getChildCount(elem): def getChildIndex(parent, toFind): """ Return the index of the given child in the given parent. - + This performs a linear search. """ JS(""" @@ -373,7 +373,7 @@ def iterChildren(elem): child = @{{getNextSibling}}(child); return lastChild; }, - 'remove': function() { + 'remove': function() { parent.removeChild(lastChild); }, __iter__: function() { @@ -419,7 +419,7 @@ def walkChildren(elem): } return lastChild; }, - 'remove': function() { + 'remove': function() { parent.removeChild(lastChild); }, __iter__: function() { @@ -427,7 +427,7 @@ def walkChildren(elem): } }; """) - + def removeEventPreview(preview): sEventPreviewStack.remove(preview) @@ -435,7 +435,7 @@ def scrollIntoView(elem): JS(""" var left = @{{elem}}.offsetLeft, top = @{{elem}}.offsetTop; var width = @{{elem}}.offsetWidth, height = @{{elem}}.offsetHeight; - + if (@{{elem}}.parentNode != @{{elem}}.offsetParent) { left -= @{{elem}}.parentNode.offsetLeft; top -= @{{elem}}.parentNode.offsetTop; @@ -532,7 +532,7 @@ def sinkEvents(element, bits): """ Set which events should be captured on a given element and passed to the registered listener. To set the listener, use setEventListener(). - + @param bits: A combination of bits; see ui.Event for bit values """ JS("@{{element}}.__eventBits = @{{bits}};") diff --git a/library/pyjamas/DOM.ie6.py b/library/pyjamas/DOM.ie6.py index 3c9b1e94c..8d860da56 100644 --- a/library/pyjamas/DOM.ie6.py +++ b/library/pyjamas/DOM.ie6.py @@ -15,7 +15,7 @@ def init(): var listener, curElem = this; while (curElem && !(listener = curElem.__listener)) curElem = curElem.parentElement; - + if (listener) @{{dispatchEvent}}($wnd.event, curElem, listener); }; @@ -107,7 +107,7 @@ def getAbsoluteLeft(elem): JS(""" // getBoundingClientRect() throws a JS exception if the elem is not attached // to the document, so we wrap it in a try/catch block - var zoomMultiple = $doc.body.parentElement.offsetWidth / + var zoomMultiple = $doc.body.parentElement.offsetWidth / $doc.body.offsetWidth; try { return Math.floor((@{{elem}}.getBoundingClientRect().left / zoomMultiple) + @@ -121,7 +121,7 @@ def getAbsoluteTop(elem): JS(""" // getBoundingClientRect() throws a JS exception if the elem is not attached // to the document, so we wrap it in a try/catch block - var zoomMultiple = $doc.body.parentElement.offsetWidth / + var zoomMultiple = $doc.body.parentElement.offsetWidth / $doc.body.offsetWidth; try { var scrollTop = $doc.parent ? $doc.parent.body.scrollTop : 0; diff --git a/library/pyjamas/DOM.mozilla.py b/library/pyjamas/DOM.mozilla.py index 5dc52afcc..1df83ac75 100644 --- a/library/pyjamas/DOM.mozilla.py +++ b/library/pyjamas/DOM.mozilla.py @@ -70,7 +70,7 @@ def getAbsoluteLeft(elem): // Please note, their implementation has 1px offset. if ( typeof @{{elem}}.getBoundingClientRect == 'function' ) { var left = Math.ceil(@{{elem}}.getBoundingClientRect().left); - + return left + $doc.body.scrollLeft + $doc.documentElement.scrollLeft; } // Older Firefox can use getBoxObjectFor @@ -83,7 +83,7 @@ def getAbsoluteLeft(elem): } parent = parent.parentNode; } - + return left + $doc.body.scrollLeft + $doc.documentElement.scrollLeft; } """) @@ -127,7 +127,7 @@ def getAbsoluteTop(elem): } parent = parent.parentNode; } - + return top + $doc.body.scrollTop + $doc.documentElement.scrollTop; } """) @@ -183,7 +183,7 @@ def releaseCapture(elem): JS(""" if ((@{{sCaptureElem}} != null) && @{{compare}}(@{{elem}}, @{{sCaptureElem}})) @{{sCaptureElem}} = null; - + if (!@{{elem}}.isSameNode) { if (@{{elem}} == $wnd.__captureElem) { $wnd.__captureElem = null; diff --git a/library/pyjamas/DOM.mshtml.py b/library/pyjamas/DOM.mshtml.py index 1014b7274..f638a0c9e 100644 --- a/library/pyjamas/DOM.mshtml.py +++ b/library/pyjamas/DOM.mshtml.py @@ -60,7 +60,7 @@ def _dispatchEvent(sender, event, useCap): curElem = sender while curElem and (get_listener(curElem) is None): curElem = curElem.parentElement - + listener = get_listener(curElem) if listener is not None: dispatchEvent(evt, curElem, listener) diff --git a/library/pyjamas/DOM.oldmoz.py b/library/pyjamas/DOM.oldmoz.py index 7a7b82a16..0e7a45115 100644 --- a/library/pyjamas/DOM.oldmoz.py +++ b/library/pyjamas/DOM.oldmoz.py @@ -113,7 +113,7 @@ def releaseCapture(elem): JS(""" if ((@{{sCaptureElem}} != null) && @{{compare}}(@{{elem}}, @{{sCaptureElem}})) @{{sCaptureElem}} = null; - + if (!@{{elem}}.isSameNode) { if (@{{elem}} == $wnd.__captureElem) { $wnd.__captureElem = null; diff --git a/library/pyjamas/DOM.py b/library/pyjamas/DOM.py index d36ad7658..dab69c372 100644 --- a/library/pyjamas/DOM.py +++ b/library/pyjamas/DOM.py @@ -927,9 +927,9 @@ def setStyleAttribute(element, name, value): element.style.setAttribute(name, value, "") def setStyleAttributes(element, **kwargs): - """ + """ multi attr: setStyleAttributes(self, {attr1:val1, attr2:val2, ...}) - """ + """ for attr, val in kwargs.items(): if hasattr(element.style, 'setProperty'): element.style.setProperty(mash_name_for_glib(attr), val, "") diff --git a/library/pyjamas/DOM.pywebkitdfb.py b/library/pyjamas/DOM.pywebkitdfb.py index f8d59313f..4df286583 100644 --- a/library/pyjamas/DOM.pywebkitdfb.py +++ b/library/pyjamas/DOM.pywebkitdfb.py @@ -11,7 +11,7 @@ def getAbsoluteLeft(elem): while (curr.offsetParent) : left -= curr.scrollLeft curr = curr.parentNode - + while (elem) : left += elem.offsetLeft @@ -23,7 +23,7 @@ def getAbsoluteLeft(elem): break elem = parent - + return left def getAbsoluteTop(elem): @@ -39,7 +39,7 @@ def getAbsoluteTop(elem): while (curr.offsetParent) : top -= curr.scrollTop curr = curr.parentNode - + while (elem) : top += elem.offsetTop @@ -49,9 +49,9 @@ def getAbsoluteTop(elem): if (parent and (parent.tagName == 'BODY') and (getStyleAttribute(elem, 'position') == 'absolute')) : break - + elem = parent - + return top diff --git a/library/pyjamas/DOM.pywebkitgtk.py b/library/pyjamas/DOM.pywebkitgtk.py index 8225d06e1..eb138a019 100644 --- a/library/pyjamas/DOM.pywebkitgtk.py +++ b/library/pyjamas/DOM.pywebkitgtk.py @@ -11,7 +11,7 @@ def getAbsoluteLeft(elem): while (curr.offsetParent) : left -= curr.scrollLeft curr = curr.parentNode - + while (elem) : left += elem.offsetLeft @@ -23,7 +23,7 @@ def getAbsoluteLeft(elem): break elem = parent - + return left def getAbsoluteTop(elem): @@ -39,7 +39,7 @@ def getAbsoluteTop(elem): while (curr.offsetParent) : top -= curr.scrollTop curr = curr.parentNode - + while (elem) : top += elem.offsetTop @@ -49,9 +49,9 @@ def getAbsoluteTop(elem): if (parent and (parent.tagName == 'BODY') and (getStyleAttribute(elem, 'position') == 'absolute')) : break - + elem = parent - + return top def buttonClick(element): diff --git a/library/pyjamas/DOM.safari.py b/library/pyjamas/DOM.safari.py index 0c3a444d9..1cb42e019 100644 --- a/library/pyjamas/DOM.safari.py +++ b/library/pyjamas/DOM.safari.py @@ -30,7 +30,7 @@ def getAbsoluteLeft(_elem): curr = curr.parentNode; } } - + while (elem) { left += elem.offsetLeft; @@ -65,7 +65,7 @@ def getAbsoluteTop(_elem): curr = curr.parentNode; } } - + while (elem) { top += elem.offsetTop; diff --git a/library/pyjamas/EventController.py b/library/pyjamas/EventController.py index b80ccf5db..37b615ac1 100644 --- a/library/pyjamas/EventController.py +++ b/library/pyjamas/EventController.py @@ -92,7 +92,7 @@ def __init__(self, parent, event_type, *args, **kwargs): def addListener(self, listener, *args, **kwargs): args = args or () kwargs = kwargs or {} - args = self.extra_args + args + args = self.extra_args + args kwargs.update(self.extra_kwargs) self.listeners[listener] = (args, kwargs) diff --git a/library/pyjamas/Factory.py b/library/pyjamas/Factory.py index 0cf824cb6..78fb768bc 100644 --- a/library/pyjamas/Factory.py +++ b/library/pyjamas/Factory.py @@ -45,7 +45,7 @@ def createWidgetOnElement(element): kwargs['Element'] = element return lookupClass(klsname)(*args, **kwargs) - + def addPyjamasNameSpace(): doc().createElementNS("urn:schemas-pyjs-org:pyjs") #try: diff --git a/library/pyjamas/HTTPRequest.browser.py b/library/pyjamas/HTTPRequest.browser.py index 76ac6e440..4fd159768 100644 --- a/library/pyjamas/HTTPRequest.browser.py +++ b/library/pyjamas/HTTPRequest.browser.py @@ -15,7 +15,7 @@ def asyncImpl(self, method, user, pwd, url, postData, handler, if user and pwd and not "Authorization" in headers: import base64 headers["Authorization"] = 'Basic %s' % (base64.b64encode('%s:%s' % (user, pwd))) - + if content_type is not None: headers["Content-Type"] = content_type if not "Content-Type" in headers: diff --git a/library/pyjamas/HTTPRequest.hulahop.py b/library/pyjamas/HTTPRequest.hulahop.py index c47f3adec..5a3d00309 100644 --- a/library/pyjamas/HTTPRequest.hulahop.py +++ b/library/pyjamas/HTTPRequest.hulahop.py @@ -27,7 +27,7 @@ def asyncGet(self, url, handler, returnxml=False, postData = None if not hasattr(handler, 'onCompletion'): raise RuntimeError("Invalid call to asyncGet: handler is not a valid request handler") - return XULrunnerHackCallback(self, 'GET', user, pwd, url, postData, + return XULrunnerHackCallback(self, 'GET', user, pwd, url, postData, handler, returnxml, content_type, headers) def asyncPost(self, url, postData, handler, returnxml=False, @@ -37,7 +37,7 @@ def asyncPost(self, url, postData, handler, returnxml=False, arguments, and it takes some extra parameters""" if not hasattr(handler, 'onCompletion'): raise RuntimeError("Invalid call to asyncPost: handler is not a valid request handler") - return XULrunnerHackCallback(self, 'POST', user, pwd, url, postData, + return XULrunnerHackCallback(self, 'POST', user, pwd, url, postData, handler, returnxml, content_type, headers) def asyncDelete(self, url, handler, returnxml=False, @@ -48,7 +48,7 @@ def asyncDelete(self, url, handler, returnxml=False, postData = None if not hasattr(handler, 'onCompletion'): raise RuntimeError("Invalid call to asyncDelete: handler is not a valid request handler") - return XULrunnerHackCallback(self, 'DELETE', user, pwd, url, postData, + return XULrunnerHackCallback(self, 'DELETE', user, pwd, url, postData, handler, returnxml, content_type, headers) def asyncPut(self, url, postData, handler, returnxml=False, @@ -58,6 +58,6 @@ def asyncPut(self, url, postData, handler, returnxml=False, arguments, and it takes some extra parameters""" if not hasattr(handler, 'onCompletion'): raise RuntimeError("Invalid call to asyncPut: handler is not a valid request handler") - return XULrunnerHackCallback(self, 'PUT', user, pwd, url, postData, + return XULrunnerHackCallback(self, 'PUT', user, pwd, url, postData, handler, returnxml, content_type, headers) diff --git a/library/pyjamas/HTTPRequest.py b/library/pyjamas/HTTPRequest.py index 2ebd23e4d..c57c8b6b4 100644 --- a/library/pyjamas/HTTPRequest.py +++ b/library/pyjamas/HTTPRequest.py @@ -16,12 +16,12 @@ def __init__(self, htr, mode, user, pwd, url, postData=None, handler=None, def callback(self): return self.htr.asyncImpl(self.mode, self.user, self.pwd, self.url, - self.postData, self.handler, self.return_xml, + self.postData, self.handler, self.return_xml, self.content_type, self.headers) class HTTPRequest(object): - def asyncGet(self, url, handler, returnxml=False, + def asyncGet(self, url, handler, returnxml=False, content_type=None, headers=None, user=None, pwd=None): postData = None if not hasattr(handler, 'onCompletion'): @@ -29,14 +29,14 @@ def asyncGet(self, url, handler, returnxml=False, return self.asyncImpl('GET', user, pwd, url, postData, handler, returnxml, content_type, headers) - def asyncPost(self, url, postData, handler, returnxml=False, + def asyncPost(self, url, postData, handler, returnxml=False, content_type=None, headers=None, user=None, pwd=None): if not hasattr(handler, 'onCompletion'): raise RuntimeError("Invalid call to asyncPost: handler is not a valid request handler") return self.asyncImpl('POST', user, pwd, url, postData, handler, returnxml, content_type, headers) - def asyncDelete(self, url, handler, returnxml=False, + def asyncDelete(self, url, handler, returnxml=False, content_type=None, headers=None, user=None, pwd=None): postData = None if not hasattr(handler, 'onCompletion'): @@ -44,7 +44,7 @@ def asyncDelete(self, url, handler, returnxml=False, return self.asyncImpl('DELETE', user, pwd, url, postData, handler, returnxml, content_type, headers) - def asyncPut(self, url, postData, handler, returnxml=False, + def asyncPut(self, url, postData, handler, returnxml=False, content_type=None, headers=None, user=None, pwd=None): if not hasattr(handler, 'onCompletion'): raise RuntimeError("Invalid call to asyncPut: handler is not a valid request handler") @@ -62,7 +62,7 @@ def onProgress(self, sender, event, ignorearg): localHandler = handlers.get(xmlHttp) if hasattr(localHandler, "onProgress"): localHandler.onProgress(event) - + def onLoad(self, sender, event, ignorearg): xmlHttp = event.target localHandler = handlers.get(xmlHttp) @@ -78,7 +78,7 @@ def onLoad(self, sender, event, ignorearg): localHandler.onCompletion(responseText) else : localHandler.onError(responseText, status) - + def onReadyStateChange(self, xmlHttp, event, ignorearg): try: xmlHttp = get_main_frame().gobject_wrap(xmlHttp) # HACK! @@ -104,7 +104,7 @@ def onReadyStateChange(self, xmlHttp, event, ignorearg): localHandler.onCompletion(responseText) else : localHandler.onError(responseText, status) - + def _convertUrlToAbsolute(self, url): uri = pygwt.getModuleBaseURL() @@ -112,7 +112,7 @@ def _convertUrlToAbsolute(self, url): # url is /somewhere. sep = uri.find('://') if not uri.startswith('file://'): - + slash = uri.find('/', sep+3) if slash > 0: uri = uri[:slash] diff --git a/library/pyjamas/History.browser.py b/library/pyjamas/History.browser.py index 320c6e964..e7911a3a1 100644 --- a/library/pyjamas/History.browser.py +++ b/library/pyjamas/History.browser.py @@ -1,24 +1,24 @@ """ Simple History management class for back/forward button support. - + This class allows your AJAX application to use a history. Each time you call newItem(), a new item is added to the history and the history - listeners are notified. If the user clicks the browser's forward or back + listeners are notified. If the user clicks the browser's forward or back buttons, the appropriate item (a string passed to newItem) is fetched from the history and the history listeners are notified. - - The address bar of the browser contains the current token, using - the "#" seperator (for implementation reasons, not because we love + + The address bar of the browser contains the current token, using + the "#" seperator (for implementation reasons, not because we love the # mark). - + You may want to check whether the hash already contains a history token when the page loads and use that to show appropriate content; this allows users of the site to store direct links in their bookmarks or send them in emails. - + To make this work properly in all browsers, you must add a specially named iframe to your html page, like this: - + <iframe id='__pygwt_historyFrame' style='width:0;height:0;border:0'></iframe> """ diff --git a/library/pyjamas/History.safari.py b/library/pyjamas/History.safari.py index 4a136d041..a15400b51 100644 --- a/library/pyjamas/History.safari.py +++ b/library/pyjamas/History.safari.py @@ -47,7 +47,7 @@ def init(): return true; """) - + def newItem(historyToken): JS(""" // Safari gets into a weird state (issue 2905) when setting the hash diff --git a/library/pyjamas/JSONService.py b/library/pyjamas/JSONService.py index 729be51c3..167f34d49 100644 --- a/library/pyjamas/JSONService.py +++ b/library/pyjamas/JSONService.py @@ -26,7 +26,7 @@ class JSONServiceError(Exception): def nextRequestID(): """ Return Next Request identifier. - MUST be a JSON scalar (String, Number, True, False), but SHOULD normally + MUST be a JSON scalar (String, Number, True, False), but SHOULD normally not be Null, and Numbers SHOULD NOT contain fractional parts. """ global __requestID, __requestIDPrefix, __lastRequestID @@ -47,8 +47,8 @@ class JSONService(object): def __init__(self, url, handler=None, headers=None): """ - Create a JSON remote service object. The url is the URL that will - receive POST data with the JSON request. See the JSON-RPC spec for + Create a JSON remote service object. The url is the URL that will + receive POST data with the JSON request. See the JSON-RPC spec for more information. The handler object should implement:: @@ -87,9 +87,9 @@ def onCompletion(self, response): pass def sendNotify(self, method, params): - # jsonrpc: A String specifying the version of the JSON-RPC protocol. + # jsonrpc: A String specifying the version of the JSON-RPC protocol. # MUST be exactly "2.0" - # If jsonrpc is missing, the server MAY handle the Request as + # If jsonrpc is missing, the server MAY handle the Request as # JSON-RPC V1.0-Request. # version: String specifying the version of the JSON-RPC protocol. # MUST be exactly "1.1" @@ -98,24 +98,24 @@ def sendNotify(self, method, params): # id: If omitted, the Request is a Notification # NOTE: JSON-RPC 1.0 uses an id of Null for Notifications. # method: A String containing the name of the procedure to be invoked. - # params: An Array or Object, that holds the actual parameter values - # for the invocation of the procedure. Can be omitted if + # params: An Array or Object, that holds the actual parameter values + # for the invocation of the procedure. Can be omitted if # empty. # NOTE: JSON-RPC 1.0 only a non-empty Array is used # From the spec of 1.1: - # The Content-Type MUST be specified and # SHOULD read + # The Content-Type MUST be specified and # SHOULD read # application/json. # The Accept MUST be specified and SHOULD read application/json. # # From http://groups.google.com/group/json-rpc/web/json-rpc-over-http - # Content-Type SHOULD be 'application/json-rpc' but MAY be + # Content-Type SHOULD be 'application/json-rpc' but MAY be # 'application/json' or 'application/jsonrequest' - # The Accept MUST be specified and SHOULD read 'application/json-rpc' + # The Accept MUST be specified and SHOULD read 'application/json-rpc' # but MAY be 'application/json' or 'application/jsonrequest'. # msg = {"jsonrpc": "2.0", "version": "1.1", - "method": method, + "method": method, "params": params } msg_data = dumps(msg) @@ -127,9 +127,9 @@ def sendNotify(self, method, params): def sendRequest(self, method, params, handler): id = nextRequestID() - msg = {"jsonrpc": "2.0", - "id": id, - "method": method, + msg = {"jsonrpc": "2.0", + "id": id, + "method": method, "params": params } msg_data = dumps(msg) @@ -168,7 +168,7 @@ def create_object(items): for (k, v) in items.items(): vars[str(k)] = v return kls(**vars) - + def _decode_response(json_str): return loads(json_str, object_hook=create_object) @@ -215,7 +215,7 @@ def onCompletion(self, json_str): ) self.request.handler.onRemoteError(0, error, self.request) elif "result" in response: - self.request.handler.onRemoteResponse(response["result"], + self.request.handler.onRemoteResponse(response["result"], self.request) else: error = dict( @@ -263,7 +263,7 @@ def __call__(self, *params, **kwargs): # reserved names: callMethod, onCompletion class JSONProxy(JSONService): def __init__(self, url, methods=None, headers=None): - self._serviceURL = url + self._serviceURL = url self.methods = methods self.headers = {} if headers is None else headers # Init with JSONService, for the use of callMethod @@ -273,19 +273,19 @@ def __init__(self, url, methods=None, headers=None): def _registerMethods(self, methods): if methods: for method in methods: - setattr(self, + setattr(self, method, - getattr(ServiceProxy(self._serviceURL, method, + getattr(ServiceProxy(self._serviceURL, method, headers=self.headers), '__call__') ) # It would be nice to use __getattr__ (instead of _registerMethods) # However, that doesn't work with pyjs and the use of _registerMethods - # saves some repeated instance creations (now only once per method and + # saves some repeated instance creations (now only once per method and # not once per call) #def __getattr__(self, name): # if not name in self.methods: - # raise AttributeError("no such method %s" % name) + # raise AttributeError("no such method %s" % name) # return ServiceProxy(self._serviceURL, name, headers=self.headers) diff --git a/library/pyjamas/Location.browser.py b/library/pyjamas/Location.browser.py index 4a41d0f55..6c5f2045c 100644 --- a/library/pyjamas/Location.browser.py +++ b/library/pyjamas/Location.browser.py @@ -2,7 +2,7 @@ class Location: def getHash(self): return JS('unescape(@{{self}}.location.hash)') - + def getSearch(self): JS("""if (@{{self}}.location.search === null) return String("?"); diff --git a/library/pyjamas/Location.opera.py b/library/pyjamas/Location.opera.py index 032735794..674f96144 100644 --- a/library/pyjamas/Location.opera.py +++ b/library/pyjamas/Location.opera.py @@ -2,6 +2,6 @@ class Location: def getHash(self): return JS('unescape(@{{self}}.location.hash)') - + def getSearch(self): return JS('unescape(@{{self}}.location.search)') diff --git a/library/pyjamas/Location.py b/library/pyjamas/Location.py index 0259614b7..81ec56c0f 100644 --- a/library/pyjamas/Location.py +++ b/library/pyjamas/Location.py @@ -18,33 +18,33 @@ def makeUrlStringFromDict(d): class Location: """ Retrieve this class by calling Window.getLocation(). - + This provides a pyjs wrapper for the current location, with some utility methods for convenience. - + """ def __init__(self, location): self.location = location self.searchDict = None - + def getHash(self): return self.location.hash - + def getHashDict(self): if not self.hashDict or self.hashDictHash != self.getHash(): self.hashDictHash = self.getHash() self.hashDict = makeUrlDict(self.getHash()[1:]) return self.hashDict - + def getHost(self): return self.location.host - + def getHostname(self): return self.location.hostname - + def getHref(self): return self.location.href - + def getPageHref(self): """ Return href with any search or hash stripped @@ -53,19 +53,19 @@ def getPageHref(self): if href.find("?"): href = href.split("?")[0] if href.find("#"): href = href.split("#")[0] return href - + def getPathname(self): return self.location.pathname - + def getPort(self): return self.location.port - + def getProtocol(self): return self.location.protocol - + def getSearch(self): return self.location.search or "" - + def getSearchDict(self): if self.searchDict is None: search = self.getSearch()[1:] @@ -74,23 +74,23 @@ def getSearchDict(self): def getSearchVar(self, key, default=None): return self.getSearchDict().get(key, default) - + def reload(self): self.location.reload() - + def setHref(self, href): self.location.href = href def setSearch(self, search): self.location.search = search - + def setSearchDict(self, searchDict): self.setSearch(makeUrlStringFromDict(searchDict)) - + def setHash(self, hash): self.location.hash = hash - + def setHashDict(self, hashDict): self.setHash(makeUrlStringFromDict(hashDict)) - + diff --git a/library/pyjamas/PyExternalMod.py b/library/pyjamas/PyExternalMod.py index a9f713f99..172d88f2a 100644 --- a/library/pyjamas/PyExternalMod.py +++ b/library/pyjamas/PyExternalMod.py @@ -66,4 +66,4 @@ def inner(*args, **kargs): return self.__parseJSON(res)['result'] JS(""" @{{self}}[@{{method}}] = @{{inner}}; - """) + """) diff --git a/library/pyjamas/Timer.mshtml.py b/library/pyjamas/Timer.mshtml.py index e38c029fa..c0058a5fb 100644 --- a/library/pyjamas/Timer.mshtml.py +++ b/library/pyjamas/Timer.mshtml.py @@ -16,14 +16,14 @@ # call into comtypes to make windows happy with python threads. class Timer: - + def __impl_init_hook(self): # we need windows to fire the function so it's happy with # python threads...so we wrap the function with this call def wrap(): pyjd.add_timer_queue(onTimer) - + onTimer = self.__onTimer self.__onTimer = wrap @@ -31,10 +31,10 @@ def __setTimeout(self, delayMillis): timer = pyjd.threading.Timer(delayMillis/1000.0, self.__fire) timer.start() return timer - + def __clearTimeout(self, timer): timer.cancel() - + def __setInterval(self, periodMillis): # wrap the call so we can repeat the interval diff --git a/library/pyjamas/Window.py b/library/pyjamas/Window.py index a1b66ba09..a11b4a4fa 100644 --- a/library/pyjamas/Window.py +++ b/library/pyjamas/Window.py @@ -78,7 +78,7 @@ def getLocation(): if not location: location = Location.Location(wnd().location) return location - + def getTitle(): return doc().title diff --git a/library/pyjamas/builder/Builder.py b/library/pyjamas/builder/Builder.py index 1fbea0d08..8c1b09e71 100644 --- a/library/pyjamas/builder/Builder.py +++ b/library/pyjamas/builder/Builder.py @@ -9,8 +9,8 @@ from pyjamas.ui.Tooltip import TooltipListener -# All event listeners with a tuple that comprises of the listener add -# function and the additional (to 'self') parameters that are expected +# All event listeners with a tuple that comprises of the listener add +# function and the additional (to 'self') parameters that are expected # for the listener. E.g., def onClick(self, sender): ... # See also pyjamas.ui.MultiListener.MultiListener.combinations eventListeners = dict( @@ -140,7 +140,7 @@ def addItem(comp, props, childs, parentInstance, eventTarget): item.setElementProperties(childitem, elemprops) # add child (by name) to item - cname = child[0]["id"] + cname = child[0]["id"] setattr(item, cname, childitem) # make the event target the recipient of all events diff --git a/library/pyjamas/builder/XMLFile.py b/library/pyjamas/builder/XMLFile.py index 5021530ee..792e50f88 100644 --- a/library/pyjamas/builder/XMLFile.py +++ b/library/pyjamas/builder/XMLFile.py @@ -93,8 +93,8 @@ def getAttrs(self, line): def getTag(self, line, requiredTags=None): mTag = self.re_tag.match(line) - if ( not mTag - or ( requiredTags is not None + if ( not mTag + or ( requiredTags is not None and mTag.group(1) not in requiredTags ) ): diff --git a/library/pyjamas/builder/__init__.py b/library/pyjamas/builder/__init__.py index 1520d4995..2c05ca0ff 100644 --- a/library/pyjamas/builder/__init__.py +++ b/library/pyjamas/builder/__init__.py @@ -1,87 +1,87 @@ -from pyjamas.ui.AbsolutePanel import AbsolutePanel -from pyjamas.ui.Anchor import Anchor -from pyjamas.ui.AreaSlider import AreaSlider +from pyjamas.ui.AbsolutePanel import AbsolutePanel +from pyjamas.ui.Anchor import Anchor +from pyjamas.ui.AreaSlider import AreaSlider from pyjamas.ui.AutoComplete import AutoCompleteTextBox -from pyjamas.ui.ButtonBase import ButtonBase -from pyjamas.ui.Button import Button -from pyjamas.ui.Calendar import Calendar -from pyjamas.ui.CaptionPanel import CaptionPanel -from pyjamas.ui.CellFormatter import CellFormatter -from pyjamas.ui.CellPanel import CellPanel -from pyjamas.ui.CheckBox import CheckBox -from pyjamas.ui.ClickDelegatePanel import ClickDelegatePanel -from pyjamas.ui.ComplexPanel import ComplexPanel -from pyjamas.ui.Composite import Composite -from pyjamas.ui.ContextMenuPopupPanel import ContextMenuPopupPanel -from pyjamas.ui.Control import Control -from pyjamas.ui.CustomButton import CustomButton -from pyjamas.ui.DeckPanel import DeckPanel -from pyjamas.ui.DecoratorPanel import DecoratorPanel -from pyjamas.ui.DialogBox import DialogBox -from pyjamas.ui.DisclosurePanel import DisclosurePanel -from pyjamas.ui.DockPanel import DockPanel -from pyjamas.ui.DoubleControl import DoubleControl -from pyjamas.ui.EventObject import EventObject -from pyjamas.ui.FileUpload import FileUpload -from pyjamas.ui.FlashPanel import FlashPanel -from pyjamas.ui.FlexCellFormatter import FlexCellFormatter -from pyjamas.ui.FlexTable import FlexTable -from pyjamas.ui.FlowPanel import FlowPanel -from pyjamas.ui.FlowTabBar import FlowTabBar -from pyjamas.ui.FocusPanel import FocusPanel -from pyjamas.ui.FocusWidget import FocusWidget -#from pyjamas.ui.FontSize import FontSize -from pyjamas.ui.FormPanel import FormPanel -from pyjamas.ui.Frame import Frame -from pyjamas.ui.GlassWidget import GlassWidget -from pyjamas.ui.Grid import Grid -from pyjamas.ui.Hidden import Hidden -from pyjamas.ui.HorizontalPanel import HorizontalPanel -from pyjamas.ui.HorizontalSlider import HorizontalSlider -from pyjamas.ui.HorizontalSplitPanel import HorizontalSplitPanel -from pyjamas.ui.HTMLLinkPanel import HTMLLinkPanel -from pyjamas.ui.HTMLPanel import HTMLPanel -from pyjamas.ui.HTML import HTML -from pyjamas.ui.HTMLTable import HTMLTable -from pyjamas.ui.HyperlinkImage import HyperlinkImage -from pyjamas.ui.Hyperlink import Hyperlink -from pyjamas.ui.Image import Image -from pyjamas.ui.InnerHTML import InnerHTML -from pyjamas.ui.InnerText import InnerText -from pyjamas.ui.InputControl import InputControl -#from pyjamas.ui.Justification import Justification -from pyjamas.ui.Label import Label -from pyjamas.ui.ListBox import ListBox +from pyjamas.ui.ButtonBase import ButtonBase +from pyjamas.ui.Button import Button +from pyjamas.ui.Calendar import Calendar +from pyjamas.ui.CaptionPanel import CaptionPanel +from pyjamas.ui.CellFormatter import CellFormatter +from pyjamas.ui.CellPanel import CellPanel +from pyjamas.ui.CheckBox import CheckBox +from pyjamas.ui.ClickDelegatePanel import ClickDelegatePanel +from pyjamas.ui.ComplexPanel import ComplexPanel +from pyjamas.ui.Composite import Composite +from pyjamas.ui.ContextMenuPopupPanel import ContextMenuPopupPanel +from pyjamas.ui.Control import Control +from pyjamas.ui.CustomButton import CustomButton +from pyjamas.ui.DeckPanel import DeckPanel +from pyjamas.ui.DecoratorPanel import DecoratorPanel +from pyjamas.ui.DialogBox import DialogBox +from pyjamas.ui.DisclosurePanel import DisclosurePanel +from pyjamas.ui.DockPanel import DockPanel +from pyjamas.ui.DoubleControl import DoubleControl +from pyjamas.ui.EventObject import EventObject +from pyjamas.ui.FileUpload import FileUpload +from pyjamas.ui.FlashPanel import FlashPanel +from pyjamas.ui.FlexCellFormatter import FlexCellFormatter +from pyjamas.ui.FlexTable import FlexTable +from pyjamas.ui.FlowPanel import FlowPanel +from pyjamas.ui.FlowTabBar import FlowTabBar +from pyjamas.ui.FocusPanel import FocusPanel +from pyjamas.ui.FocusWidget import FocusWidget +#from pyjamas.ui.FontSize import FontSize +from pyjamas.ui.FormPanel import FormPanel +from pyjamas.ui.Frame import Frame +from pyjamas.ui.GlassWidget import GlassWidget +from pyjamas.ui.Grid import Grid +from pyjamas.ui.Hidden import Hidden +from pyjamas.ui.HorizontalPanel import HorizontalPanel +from pyjamas.ui.HorizontalSlider import HorizontalSlider +from pyjamas.ui.HorizontalSplitPanel import HorizontalSplitPanel +from pyjamas.ui.HTMLLinkPanel import HTMLLinkPanel +from pyjamas.ui.HTMLPanel import HTMLPanel +from pyjamas.ui.HTML import HTML +from pyjamas.ui.HTMLTable import HTMLTable +from pyjamas.ui.HyperlinkImage import HyperlinkImage +from pyjamas.ui.Hyperlink import Hyperlink +from pyjamas.ui.Image import Image +from pyjamas.ui.InnerHTML import InnerHTML +from pyjamas.ui.InnerText import InnerText +from pyjamas.ui.InputControl import InputControl +#from pyjamas.ui.Justification import Justification +from pyjamas.ui.Label import Label +from pyjamas.ui.ListBox import ListBox from pyjamas.ui.Map import ImageMap, MapArea -from pyjamas.ui.MenuBarPopupPanel import MenuBarPopupPanel -from pyjamas.ui.MenuBar import MenuBar -from pyjamas.ui.MenuItem import MenuItem -from pyjamas.ui.MouseInputControl import MouseInputControl -from pyjamas.ui.NamedFrame import NamedFrame -from pyjamas.ui.Panel import Panel -from pyjamas.ui.PasswordTextBox import PasswordTextBox -from pyjamas.ui.PopupPanel import PopupPanel -from pyjamas.ui.PushButton import PushButton -from pyjamas.ui.RadioButton import RadioButton -from pyjamas.ui.RichTextArea import RichTextArea -from pyjamas.ui.RootPanel import RootPanel -from pyjamas.ui.RowFormatter import RowFormatter -from pyjamas.ui.ScrollPanel import ScrollPanel -from pyjamas.ui.SimplePanel import SimplePanel -from pyjamas.ui.SplitPanel import SplitPanel -from pyjamas.ui.StackPanel import StackPanel -from pyjamas.ui.TabBar import TabBar -from pyjamas.ui.TabPanel import TabPanel -from pyjamas.ui.TextArea import TextArea -from pyjamas.ui.TextBoxBase import TextBoxBase -from pyjamas.ui.TextBox import TextBox -from pyjamas.ui.ToggleButton import ToggleButton -from pyjamas.ui.Tooltip import Tooltip -from pyjamas.ui.TreeContentPanel import TreeContentPanel -from pyjamas.ui.TreeItem import TreeItem -from pyjamas.ui.Tree import Tree -from pyjamas.ui.UIObject import UIObject -from pyjamas.ui.VerticalPanel import VerticalPanel -from pyjamas.ui.VerticalSlider import VerticalSlider -from pyjamas.ui.VerticalSplitPanel import VerticalSplitPanel -from pyjamas.ui.Widget import Widget +from pyjamas.ui.MenuBarPopupPanel import MenuBarPopupPanel +from pyjamas.ui.MenuBar import MenuBar +from pyjamas.ui.MenuItem import MenuItem +from pyjamas.ui.MouseInputControl import MouseInputControl +from pyjamas.ui.NamedFrame import NamedFrame +from pyjamas.ui.Panel import Panel +from pyjamas.ui.PasswordTextBox import PasswordTextBox +from pyjamas.ui.PopupPanel import PopupPanel +from pyjamas.ui.PushButton import PushButton +from pyjamas.ui.RadioButton import RadioButton +from pyjamas.ui.RichTextArea import RichTextArea +from pyjamas.ui.RootPanel import RootPanel +from pyjamas.ui.RowFormatter import RowFormatter +from pyjamas.ui.ScrollPanel import ScrollPanel +from pyjamas.ui.SimplePanel import SimplePanel +from pyjamas.ui.SplitPanel import SplitPanel +from pyjamas.ui.StackPanel import StackPanel +from pyjamas.ui.TabBar import TabBar +from pyjamas.ui.TabPanel import TabPanel +from pyjamas.ui.TextArea import TextArea +from pyjamas.ui.TextBoxBase import TextBoxBase +from pyjamas.ui.TextBox import TextBox +from pyjamas.ui.ToggleButton import ToggleButton +from pyjamas.ui.Tooltip import Tooltip +from pyjamas.ui.TreeContentPanel import TreeContentPanel +from pyjamas.ui.TreeItem import TreeItem +from pyjamas.ui.Tree import Tree +from pyjamas.ui.UIObject import UIObject +from pyjamas.ui.VerticalPanel import VerticalPanel +from pyjamas.ui.VerticalSlider import VerticalSlider +from pyjamas.ui.VerticalSplitPanel import VerticalSplitPanel +from pyjamas.ui.Widget import Widget diff --git a/library/pyjamas/chart/Annotation.py b/library/pyjamas/chart/Annotation.py index 1a2dccab7..166352551 100644 --- a/library/pyjamas/chart/Annotation.py +++ b/library/pyjamas/chart/Annotation.py @@ -50,10 +50,10 @@ def getNumberOfCharsWide(s): result = 0 if not s.startswith("<html>"): result = len(s) - + else: result = htmlWidth(s) - + return result class Annotation: @@ -75,7 +75,7 @@ def __init__(self): self.numberOfCharsWide = 0 self.widthUpperBound = NAI self.heightUpperBound = NAI - + """ * Computes parameters used to estimate the width and height * of the (invisible) enclosing 1x1 Grid of an annotation @@ -88,14 +88,14 @@ def analyzeHTML(self, s): self._isHTML = False self.numberOfLinesHigh = 0 self.numberOfCharsWide = 0 - + elif hasattr(s, "startswith") and not s.startswith("<html>"): # no html==>plain text self._isHTML = False self.numberOfLinesHigh = 1 self.numberOfCharsWide = len(s) result = s - + else: # HTML self._isHTML = True @@ -103,81 +103,81 @@ def analyzeHTML(self, s): result = s[HTML_LEN:] if self.widthUpperBound == NAI: self.numberOfCharsWide = htmlWidth(result) - - + + if self.heightUpperBound == NAI: self.numberOfLinesHigh = htmlHeight(result) - - - + + + return result - - - + + + def getFontColor(self): return self.fontColor - + def getFontSize(self): return self.fontSize - - + + def getLocation(self): return self.location - - + + def isHTML(self): return self._isHTML - - + + def getText(self): if self._isHTML: return "<html>" + (self.text or "") return self.text - + def getVisible(self): return self.visible - + def getXShift(self): return self.xShift - + def getYShift(self): return self.yShift - - + + def setFontColor(self, cssColor): self.fontColor = cssColor - + def setFontSize(self, fontSize): self.fontSize = fontSize - + def setFontWeight(self, cssWeight): self.fontWeight = cssWeight - + def setFontStyle(self, cssStyle): self.fontStyle = cssStyle - - + + def getFontWeight(self): return self.fontWeight - + def getFontStyle(self): return self.fontStyle - - + + def setLocation(self, location): self.location = location - - + + def setText(self, text, widthUpperBound=NAI, heightUpperBound=NAI): self.widthUpperBound = widthUpperBound self.heightUpperBound = heightUpperBound self.text = self.analyzeHTML(text) self.widget = None - + def setVisible(self, visible): self.visible = visible - - + + def setWidget(self, widget, widthUpperBound=DEFAULT_WIDGET_WIDTH_UPPERBOUND, heightUpperBound=DEFAULT_WIDGET_HEIGHT_UPPERBOUND): @@ -187,44 +187,44 @@ def setWidget(self, widget, self.heightUpperBound = heightUpperBound self.text = None self.widget = widget - + def getWidget(self): return self.widget - - + + def setXShift(self, xShift): self.xShift = xShift - + def setYShift(self, yShift): self.yShift = yShift - - + + def getHeightUpperBound(self): result = 0 if self.heightUpperBound != NAI: result = self.heightUpperBound - + else: result = int (math.ceil(self.fontSize * self.numberOfLinesHigh * CHARHEIGHT_TO_FONTSIZE_UPPERBOUND)) - + return result - - + + def getWidthUpperBound(self): result = 0 if self.widthUpperBound != NAI: result = self.widthUpperBound - + else: result = int ( math.ceil(self.fontSize * self.numberOfCharsWide * CHARWIDTH_TO_FONTSIZE_UPPERBOUND)) - + return result - - + + # end of class Annotation diff --git a/library/pyjamas/chart/AnnotationLocation.py b/library/pyjamas/chart/AnnotationLocation.py index f884f1f3e..30c54f640 100644 --- a/library/pyjamas/chart/AnnotationLocation.py +++ b/library/pyjamas/chart/AnnotationLocation.py @@ -42,8 +42,8 @@ def getAnnotationLocation(widthMultiplier, heightMultiplier): # assumes both multiplier are -1, 0, or 1 result = locationMap[heightMultiplier+1][widthMultiplier+1] return result - - + + # Negative width or height "turn the symbol inside-out", # requiring a corresponding "reflection" of annotation # location (only needed for baseline-based bar symbols) @@ -53,7 +53,7 @@ def transform(a, signWidth, signHeight): result = getAnnotationLocation( signWidth*a.widthMultiplier, signHeight*a.heightMultiplier) - + return result @@ -93,7 +93,7 @@ def transform(a, signWidth, signHeight): ** *""" class AnnotationLocation: - + # these multiply the width and height of the annotation and # the symbol it is attached to in order to define the # center of the annotation (see equations in later code), @@ -102,7 +102,7 @@ def __init__(self, widthMultiplier, heightMultiplier): validateMultipliers(widthMultiplier, heightMultiplier) self.widthMultiplier = widthMultiplier self.heightMultiplier = heightMultiplier - + # These define the alignment of the label within it's # containing 1 x 1 Grid. For example, if this # containing grid is to the left of the labeled @@ -113,21 +113,21 @@ def __init__(self, widthMultiplier, heightMultiplier): def getHorizontalAlignment(self): if self.widthMultiplier == -1: result = HasHorizontalAlignment.ALIGN_RIGHT - + elif self.widthMultiplier == 0: result = HasHorizontalAlignment.ALIGN_CENTER - + elif self.widthMultiplier == 1: result = HasHorizontalAlignment.ALIGN_LEFT - + else: raise IllegalStateException( "Invalid widthMultiplier: " + str(self.widthMultiplier) + " 1, 0, or -1 were expected.") - + return result - - + + """ Given the x-coordinate at the center of the symbol * that this annotation annotates, the annotation's * width, and the symbol's width, this method returns @@ -138,34 +138,34 @@ def getUpperLeftX(self, x, w, symbolW): result = int (round(x + (self.widthMultiplier * (w + symbolW) - w)/2.) ) return result - - + + """ analogous to getUpperLeftX, except for the y-coordinate """ def getUpperLeftY(self, y, h, symbolH): result = int (round(y + (self.heightMultiplier * (h + symbolH) - h)/2.)) return result - + # analogous to getHorizontalAlignment def getVerticalAlignment(self): if self.heightMultiplier == -1: result = HasVerticalAlignment.ALIGN_BOTTOM - + elif self.heightMultiplier == 0: result = HasVerticalAlignment.ALIGN_MIDDLE - + elif self.heightMultiplier == 1: result = HasVerticalAlignment.ALIGN_TOP - + else: raise IllegalStateException( "Invalid heightMultiplier: " + self.heightMultiplier + " -1, 0, or 1 were expected.") - + return result - - - + + + """ * This method returns the annotation location whose * "attachment point" keeps the annotation either @@ -214,14 +214,14 @@ def decodePieLocation(self, thetaMid): pieTransformedHeightMultiplier = self.heightMultiplier else: pieTransformedHeightMultiplier = 0 - + return getAnnotationLocation(pieTransformedWidthMultiplier, pieTransformedHeightMultiplier) - - - + + + # end of class AnnotationLocation - + # non-tagging-only locations used by ANCHOR_MOUSE_* symbol types AT_THE_MOUSE = AnnotationLocation(0,0) AT_THE_MOUSE_SNAP_TO_X = AnnotationLocation(0,0) diff --git a/library/pyjamas/chart/Axis.py b/library/pyjamas/chart/Axis.py index 39bb0d9f2..20f9f76b7 100644 --- a/library/pyjamas/chart/Axis.py +++ b/library/pyjamas/chart/Axis.py @@ -30,7 +30,7 @@ from pyjamas.chart.GChartConsts import NAI from pyjamas.chart.GChartConsts import DEFAULT_TICK_COUNT -from pyjamas.chart.GChartConsts import DEFAULT_WIDGET_WIDTH_UPPERBOUND +from pyjamas.chart.GChartConsts import DEFAULT_WIDGET_WIDTH_UPPERBOUND from pyjamas.chart.GChartConsts import DEFAULT_WIDGET_HEIGHT_UPPERBOUND from pyjamas.chart.GChartConsts import DEFAULT_TICK_LABEL_FONT_COLOR from pyjamas.chart.GChartConsts import DEFAULT_TICK_LABEL_FONTSIZE @@ -48,8 +48,8 @@ from pyjamas.chart.GChartConsts import XTICKS_ID from pyjamas.chart.GChartConsts import XGRIDLINES_ID from pyjamas.chart.GChartConsts import XAXIS_ID -from pyjamas.chart.GChartConsts import TICK_CHARHEIGHT_TO_FONTSIZE_LOWERBOUND -from pyjamas.chart.GChartConsts import TICK_CHARWIDTH_TO_FONTSIZE_LOWERBOUND +from pyjamas.chart.GChartConsts import TICK_CHARHEIGHT_TO_FONTSIZE_LOWERBOUND +from pyjamas.chart.GChartConsts import TICK_CHARWIDTH_TO_FONTSIZE_LOWERBOUND from pyjamas.chart.GChartConsts import Y_AXIS from pyjamas.chart.GChartConsts import Y2_AXIS @@ -193,41 +193,41 @@ def _addTickLabel(self, tickPosition, tickLabel, widthUpperBound, heightUpperBou Adds a tick at the specified position with the specified label on this axis, whose width and height are within the specified upper-bounds. - + <p> Note that explicitly adding a single tick via this method will eliminate any auto-generated ticks associated with the <tt>setTickCount</tt> method. - + <p> Use this method to specify unusually spaced tick marks with labels that do not directly reflect the position (for example, for a logarithmic axis, or for a bar chart with special keyword-type labels, or a time axis that places date and time on two separate lines). - + @param tickPosition the position, in model units, along this axis at which the tick is displayed. For example, if the axis range goes from 0 to 1, a tick at position 0.5 would appear in the middle of the axis. - + @param tickLabel the label for this tick. HTML is supported in tick labels, but it must be prefixed by <tt><html></tt>. See the {@link Curve.Point#setAnnotationText(String,int,int) setAnnotationText} method for more information. - + @param widthUpperBound an upper bound on the width of the text or HTML, in pixels. Use <tt>NAI</tt> to get GChart to estimate this width for you. See the <tt>setAnnotationText</tt> method for more information. - + @param heightUpperBound an upper bound on the height of the text or HTML, in pixels. Use <tt>NAI</tt> to get GChart to estimate this height for you. See the <tt>setAnnotationText</tt> method for more information. - + @see #clearTicks clearTicks @see #addTick(double) addTick(double) @see #addTick(double,String) addTick(double,String) @@ -241,7 +241,7 @@ def _addTickLabel(self, tickPosition, tickLabel, widthUpperBound, heightUpperBou @see Curve.Point#setAnnotationText(String,int,int) setAnnotationText @see Curve.Point#setAnnotationWidget setAnnotationWidget - + """ self.chartDecorationsChanged = True if NAI != self.tickCount: diff --git a/library/pyjamas/chart/GChart.py b/library/pyjamas/chart/GChart.py index fe142d9f8..60b4e299b 100644 --- a/library/pyjamas/chart/GChart.py +++ b/library/pyjamas/chart/GChart.py @@ -71,7 +71,7 @@ from pyjamas.chart.GChartConsts import FOOTNOTES_ID from pyjamas.chart.GChartConsts import HOVER_CURSOR_ID from pyjamas.chart.GChartConsts import HOVER_ANNOTATION_ID -from pyjamas.chart.GChartConsts import N_PRE_SYSTEM_CURVES +from pyjamas.chart.GChartConsts import N_PRE_SYSTEM_CURVES from pyjamas.chart.GChartConsts import N_POST_SYSTEM_CURVES from pyjamas.chart.GChartConsts import DEFAULT_GRID_COLOR from pyjamas.chart.GChartConsts import GRID_BORDER_STYLE @@ -81,10 +81,10 @@ from pyjamas.chart.GChartConsts import TICK_BORDER_STYLE from pyjamas.chart.GChartConsts import TICK_BORDER_WIDTH from pyjamas.chart.GChartConsts import Y2_AXIS -from pyjamas.chart.GChartConsts import DEFAULT_TITLE_THICKNESS +from pyjamas.chart.GChartConsts import DEFAULT_TITLE_THICKNESS from pyjamas.chart.GChartConsts import DEFAULT_FOOTNOTES_THICKNESS from pyjamas.chart.GChartConsts import TICK_CHARWIDTH_TO_FONTSIZE_LOWERBOUND -from pyjamas.chart.GChartConsts import TRANSPARENT_BORDER_COLOR +from pyjamas.chart.GChartConsts import TRANSPARENT_BORDER_COLOR from pyjamas.chart.GChartConsts import YAxisId from pyjamas.chart import Double @@ -94,9 +94,9 @@ from pyjamas.chart import TouchedPointUpdateOption from pyjamas.chart.Curve import Curve -from pyjamas.chart import GChartUtil +from pyjamas.chart import GChartUtil from pyjamas.chart.GChartWidgets import PlotPanel -from pyjamas.chart import GChartWidgets +from pyjamas.chart import GChartWidgets import pygwt from pyjamas.chart.Axis import XAxis, YAxis, Y2Axis @@ -3483,7 +3483,7 @@ def update(self, option=None): # constructs the chart within the chart panel from current specs def assembleChart(self): - if (self.chartDecorationsChanged or self.xAxis.limitsChanged() or + if (self.chartDecorationsChanged or self.xAxis.limitsChanged() or self.yAxis.limitsChanged() or self.y2Axis.limitsChanged()): self.plotPanel.reset(self.xChartSize, self.yChartSize, @@ -3654,7 +3654,7 @@ def setDefaultBorderColor(self, curve, index): # renders the curve in the plot panel def realizeCurve(self, c): if c.isValidated(): - return + return internalIndex = self.getInternalCurveIndex(c) rpIndex = self.getRenderingPanelIndex(internalIndex) grp = self.plotPanel.getGraphicsRenderingPanel(rpIndex) @@ -3669,8 +3669,8 @@ def realizeCurve(self, c): c.setWasCanvasRendered(False) # continuous fill# non-empty fill# canvas available - elif (0 == c.getSymbol().getFillSpacing() and - 0 < c.getSymbol().getFillThickness() and + elif (0 == c.getSymbol().getFillSpacing() and + 0 < c.getSymbol().getFillThickness() and None != self.getCanvasFactory() and c.isVisible()): grp.maybeAddCanvas() diff --git a/library/pyjamas/chart/GChartWidgets.py b/library/pyjamas/chart/GChartWidgets.py index e6a675bd1..79d867e2e 100644 --- a/library/pyjamas/chart/GChartWidgets.py +++ b/library/pyjamas/chart/GChartWidgets.py @@ -514,8 +514,8 @@ def getNextOrNewAlignedLabel(self, fontSize, fontStyle, fontWeight, fontColor, h * """ e = labelWidget.getElement() - if (None == e or - (DOM.getParent(e) != + if (None == e or + (DOM.getParent(e) != result.innerGrid.getCellFormatter().getElement(0,0))): # the widget' DOM parent isn't label's grid-cell (it was moved) result.labelWidget = None @@ -629,12 +629,12 @@ def setReusableProperties(self, backgroundColor, borderColor, borderStyle, borde newW = int ( round(xD + dWidth) - newX ) newY = int ( round(yD) ) newH = int ( round(yD + dHeight) - newY ) - thickness = min(newW, newH) + thickness = min(newW, newH) # Don't allow borders that would exceed specified width or # height. So, if smaller of width, height is at least twice the # border width, border width is used as is, otherwise, # it's replaced with half the smaller of width, height: - newCappedBorderWidthX2 = min (2*borderWidth, thickness) + newCappedBorderWidthX2 = min (2*borderWidth, thickness) """ * Note: on a GWT absolute panel, the x,y position of the widget is the @@ -961,7 +961,7 @@ def addOrRevealImage(self, backgroundColor, borderColor, borderStyle, borderWidt def renderBorderedImage(self, backgroundColor, borderColor, borderStyle, borderWidth, width, height, x, y, url): # if None != canvas and url == getBlankImageURL() and (borderStyle == USE_CSS or borderStyle.equals("solid")): -# # +# # # # Use canvas to emulate a transparent, bordered image # # (GChart can only render solid borders and blank image URLS # # with canvas at this point) @@ -1058,8 +1058,8 @@ def __init__(self, chart, **kwargs): def addGraphicsRenderingPanel(self, rpIndex): domInsert = True w = GraphicsRenderingPanel(self.chart) - if (DECORATIVE_RENDERING_PANEL_INDEX == rpIndex or - self.chart.isHoverFeedbackRenderingPanel(rpIndex) or + if (DECORATIVE_RENDERING_PANEL_INDEX == rpIndex or + self.chart.isHoverFeedbackRenderingPanel(rpIndex) or not self.chart.getClipToPlotArea()): # chart decorations and hover feedback are never clipped w.setPixelSize(0, 0) @@ -1181,7 +1181,7 @@ def setClientX(self, clientX, isClick): if (NAI == clientX): self.xMouse = NAI else: - self.xMouse = (Window.getScrollLeft() + clientX - + self.xMouse = (Window.getScrollLeft() + clientX - self.getAbsoluteLeft()) def getClientY(self): @@ -1199,7 +1199,7 @@ def setClientY(self, clientY, isClick): if (NAI == clientY): self.yMouse = NAI else: - self.yMouse = (Window.getScrollTop() + clientY - + self.yMouse = (Window.getScrollTop() + clientY - self.getAbsoluteTop()) @@ -1342,8 +1342,8 @@ def reset(self, xChartSize, yChartSize, hasYAxis, hasY2Axis, xAxis, yAxis, y2Axi # their clipping specs into agreement with the chartspecs for i in range(self.getRenderingPanelCount()): grp = self.graphicsPanel.getWidget(i) - if (DECORATIVE_RENDERING_PANEL_INDEX == i or - self.chart.isHoverFeedbackRenderingPanel(i) or + if (DECORATIVE_RENDERING_PANEL_INDEX == i or + self.chart.isHoverFeedbackRenderingPanel(i) or not self.chart.getClipToPlotArea()): grp.setPixelSize(0, 0) GChartUtil.setOverflow(grp, "visible") @@ -1410,8 +1410,8 @@ def dxToPixel(self, dx): def yToChartPixel(self, y, isY2): if isY2: - minY = self.y2Min - maxY = self.y2Max + minY = self.y2Min + maxY = self.y2Max else: minY = self.yMin maxY = self.yMax @@ -1432,8 +1432,8 @@ def yToChartPixel(self, y, isY2): def yToPixel(self, y, isY2): if isY2: - minY = self.y2Min - maxY = self.y2Max + minY = self.y2Min + maxY = self.y2Max else: minY = self.yMin maxY = self.yMax @@ -1481,8 +1481,8 @@ def yPixelToY2(self, yPx): def dyToPixel(self, dy, isY2): if isY2: - minY = self.y2Min - maxY = self.y2Max + minY = self.y2Min + maxY = self.y2Max else: minY = self.yMin maxY = self.yMax @@ -1857,7 +1857,7 @@ def isOverOpenedHoverAnnotation(self, event): result = True elif self.isGeometricallyContainedIn(hoverElement, - DOM.eventGetClientX(event), + DOM.eventGetClientX(event), DOM.eventGetClientY(event)): result = True @@ -1895,7 +1895,7 @@ def takesUsCompletelyOutsideChart(self, event): result = False elif self.isGeometricallyContainedIn(self.getElement(), - DOM.eventGetClientX(event), + DOM.eventGetClientX(event), DOM.eventGetClientY(event)): result = False @@ -2056,7 +2056,7 @@ def onBrowserEvent(self, event): if self.chart.getHoverTouchingEnabled() or isClick: self.setClientX(DOM.eventGetClientX(event), isClick) self.setClientY(DOM.eventGetClientY(event), isClick) - if (not self.chart.isUpdateNeeded() and + if (not self.chart.isUpdateNeeded() and self.touchObjectAtMousePosition(isClick)): self.chart.assembleChart() @@ -2071,7 +2071,7 @@ def onBrowserEvent(self, event): """ self.setClientX(NAI, False); # mouse not over chart, self.setClientY(NAI, False); # so position is undefined - if (not self.chart.isUpdateNeeded() and + if (not self.chart.isUpdateNeeded() and self.touchObjectAtMousePosition()): self.chart.assembleChart() diff --git a/library/pyjamas/chart/Point.py b/library/pyjamas/chart/Point.py index 7e7e32222..5d9615aad 100644 --- a/library/pyjamas/chart/Point.py +++ b/library/pyjamas/chart/Point.py @@ -451,7 +451,7 @@ def setAnnotationLocation(self, annotationLocation): ** @see Axis#addTick(double,String,int,int) addTick ** *""" - def setAnnotationText(self, annotationText, + def setAnnotationText(self, annotationText, widthUpperBound=NAI, heightUpperBound=NAI): self.getParent().invalidate() diff --git a/library/pyjamas/chart/Symbol.py b/library/pyjamas/chart/Symbol.py index 42c3d2c6f..be263ce10 100644 --- a/library/pyjamas/chart/Symbol.py +++ b/library/pyjamas/chart/Symbol.py @@ -41,10 +41,10 @@ ** *""" class Symbol(object): - + def __init__(self, parent): self.parent = parent - + self.annotation = None self.backgroundColor = GChartConsts.DEFAULT_SYMBOL_BACKGROUND_COLOR # same as backgroundColor, but with extended RGBA collapsed to plain RGA @@ -109,8 +109,8 @@ def __init__(self, parent): self.width = GChartConsts.DEFAULT_SYMBOL_WIDTH self.xScaleFactor = 1.0 self.yScaleFactor = 1.0 - - + + def getBackgroundColor(self): """* Returns the CSS background color of all the rectangular ** elements used in rendering the symbol. @@ -122,10 +122,10 @@ def getBackgroundColor(self): ** @see #setBackgroundColor(String) setBackgroundColor *""" return self.backgroundColor - + def getBackgroundColorCSS(self): return self.backgroundColorCSS - + def getBaseline(self): """* Returns the baseline value for this symbol, ** previously specified via <tt>setBaseline</tt> @@ -137,7 +137,7 @@ def getBaseline(self): ** @see #setBaseline setBaseline *""" return self.baseline - + def getBorderColor(self): """* Returns the CSS border color of all the rectangular ** elements used in rendering the symbol. @@ -150,10 +150,10 @@ def getBorderColor(self): ** *""" return self.borderColor - + def getBorderColorCSS(self): return self.borderColorCSS - + """* ** Returns the border style of all of the rectangular ** elements from which this symbol is built. @@ -165,8 +165,8 @@ def getBorderColorCSS(self): *""" def getBorderStyle(self): return self.borderStyle - - + + """* ** Returns the width of the border around each ** rectangular element used to render this symbol, @@ -179,7 +179,7 @@ def getBorderStyle(self): """ def getBorderWidth(self): return self.borderWidth - + """* * * Returns the height of the rectangular "brush" that defines @@ -195,8 +195,8 @@ def getBorderWidth(self): """ def getBrushHeight(self): return self.brushHeight - - + + """* * * Returns the location of the rectangular brush relative to @@ -210,9 +210,9 @@ def getBrushHeight(self): """ def getBrushLocation(self): return self.brushLocation - - - + + + """* * * Returns the width of the rectangular "brush" that defines @@ -228,8 +228,8 @@ def getBrushLocation(self): """ def getBrushWidth(self): return self.brushWidth - - + + """* ** @deprecated ** @@ -240,9 +240,9 @@ def getBrushWidth(self): *""" def getFillHasHovertext(self): return self.fillHasHovertext - - - + + + """* ** Returns the spacing between successive rectangular ** elements used to emulate any required non-rectangular @@ -261,12 +261,12 @@ def getFillHasHovertext(self): def getFillSpacing(self): if Double.NaN==(self.fillSpacing): return self.symbolType.defaultFillSpacing() - + else: return self.fillSpacing - - - + + + """* ** Returns the "thickness" of rectangular elements used to ** emulate any required non-rectangular features of the symbol. @@ -283,21 +283,21 @@ def getFillSpacing(self): def getFillThickness(self): if self.fillThickness==GChartConsts.NAI: return self.symbolType.defaultFillThickness() - + else: return self.fillThickness - - - + + + """ Retrieves the annotation that defines the properties of * the internally generated annotations used to display * hover feedback. """ def getHoverAnnotation(self): if self.hoverAnnotation is None: self.hoverAnnotation = Annotation() - + return self.hoverAnnotation - + """* * Retrieves a boolean that indicates if point-specific * annotations popup whenever you hover over a point on the @@ -310,7 +310,7 @@ def getHoverAnnotation(self): """ def getHoverAnnotationEnabled(self): return self.hoverAnnotationEnabled - + """* ** Retrieves the weight of the font that will be used ** with this symbol's hover annotations. @@ -328,7 +328,7 @@ def getHoverAnnotationEnabled(self): def getHoverFontWeight(self): result = self.getHoverAnnotation().getFontWeight() return result - + """* ** Retrieves the font color of this symbol's hover ** annotations. @@ -341,9 +341,9 @@ def getHoverFontWeight(self): def getHoverFontColor(self): result = self.getHoverAnnotation().getFontColor() return result - - - + + + """* ** Retrieves the CSS font-style used with this symbol's ** hover annotations. @@ -357,7 +357,7 @@ def getHoverFontColor(self): def getHoverFontStyle(self): result = self.getHoverAnnotation().getFontStyle() return result - + """* ** Retrieves the CSS font size used with this symbol's hover ** annotations, in pixels. @@ -371,8 +371,8 @@ def getHoverFontStyle(self): def getHoverFontSize(self): result = self.getHoverAnnotation().getFontSize() return result - - + + """* * Retrieves point-relative location of this symbol's hover * annotations. <p> @@ -388,9 +388,9 @@ def getHoverLocation(self): result = self.getHoverAnnotation().getLocation() if None == result: result = self.getSymbolType().defaultHoverLocation() - + return result - + """* * Retrieves the symbol type that will determine how the * hover annotations for this symbol gets positioned. @@ -405,7 +405,7 @@ def getHoverLocation(self): """ def getHoverAnnotationSymbolType(self): return self.hoverAnnotationSymbolType - + """* * Retrieves the background color used to indicate that the mouse is * "touching" (hovering over) a point. @@ -418,7 +418,7 @@ def getHoverAnnotationSymbolType(self): """ def getHoverSelectionBackgroundColor(self): return self.hoverSelectionBackgroundColor - + """* * Retrieves the border color used to indicate that the mouse is * "touching" (hovering over) a point. @@ -431,7 +431,7 @@ def getHoverSelectionBackgroundColor(self): """ def getHoverSelectionBorderColor(self): return self.hoverSelectionBorderColor - + """* * Retrieves the border style used to indicate that the mouse is * "touching" (hovering over) a point. @@ -444,7 +444,7 @@ def getHoverSelectionBorderColor(self): """ def getHoverSelectionBorderStyle(self): return self.hoverSelectionBorderStyle - + """* * Retrieves the width of the border around the perimeter of * rectangles used to indicate that the mouse is @@ -461,7 +461,7 @@ def getHoverSelectionBorderStyle(self): """ def getHoverSelectionBorderWidth(self): return self.hoverSelectionBorderWidth - + """* * Retrieves a boolean that indicates if hover selection * feedback will be provided for this curve. <p> @@ -475,8 +475,8 @@ def getHoverSelectionBorderWidth(self): """ def getHoverSelectionEnabled(self): return self.hoverSelectionEnabled - - + + """* * Returns the fill spacing that will be used when * rendering this curve's hover selection feedback. @@ -492,7 +492,7 @@ def getHoverSelectionEnabled(self): """ def getHoverSelectionFillSpacing(self): return self.hoverSelectionFillSpacing - + """* * Returns the fill thickness that will be used when * rendering this curve's hover selection feedback. @@ -508,8 +508,8 @@ def getHoverSelectionFillSpacing(self): """ def getHoverSelectionFillThickness(self): return self.hoverSelectionFillThickness - - + + """* * Returns the height of the symbol used to indicate * when a given point is being "hovered over" with the @@ -527,8 +527,8 @@ def getHoverSelectionFillThickness(self): """ def getHoverSelectionHeight(self): return self.hoverSelectionHeight - - + + """* * Returns the URL that will be used for all of the * images used in rendering this symbol's selection feedback. @@ -541,14 +541,14 @@ def getHoverSelectionHeight(self): * with this symbol. * """ - + def getHoverSelectionImageURL(self): if self.hoverSelectionImageURL: return self.hoverSelectionImageURL return self.parent.chart.getBlankImageURL() - - - + + + """* * * Returns the symbol type that GChart will use when generating @@ -567,7 +567,7 @@ def getHoverSelectionImageURL(self): """ def getHoverSelectionSymbolType(self): return self.hoverSelectionSymbolType - + """* * Returns the width of the symbol used to indicate * when a given point is being "hovered over" with the @@ -586,8 +586,8 @@ def getHoverSelectionSymbolType(self): """ def getHoverSelectionWidth(self): return self.hoverSelectionWidth - - + + """* ** Returns the hovertextTemplate of this symbol. ** <p> @@ -601,12 +601,12 @@ def getHoverSelectionWidth(self): def getHovertextTemplate(self): if None == self.hovertextTemplate: return self.symbolType.defaultHovertextTemplate() - + else: return self.hovertextTemplate - - - + + + """* * When widget-based hover annotations are being used * by the curve associated with this symbol, this method returns @@ -623,11 +623,11 @@ def getHovertextTemplate(self): """ def getHoverWidget(self): return self.getHoverAnnotation().getWidget() - - - - - + + + + + """* * Retrieves the number of pixels (along the x-axis) that * this point's hover-annotation will be moved from its default, @@ -642,8 +642,8 @@ def getHoverWidget(self): def getHoverXShift(self): result = self.getHoverAnnotation().getXShift() return result - - + + """* * Retrieves the number of pixels (along the y-axis) that * this point's hover annotation will be moved from its default, @@ -658,8 +658,8 @@ def getHoverXShift(self): def getHoverYShift(self): result = self.getHoverAnnotation().getYShift() return result - - + + """* * Returns the URL that will be used for all of the * images used in rendering this symbol. @@ -675,16 +675,16 @@ def getImageURL(self): if self.imageURL: return self.imageURL return self.parent.chart.getBlankImageURL() - + # returns an internal, parsed form of the hovertext template def getHovertextChunks(self): if None == self.hovertextChunks: self.hovertextChunks = HovertextChunk.parseHovertextTemplate( self.getHovertextTemplate()) - + return self.hovertextChunks - - + + """* Returns the <tt>GChart</tt> that contains this ** <tt>Symbol</tt>. ** @@ -694,7 +694,7 @@ def getHovertextChunks(self): *""" def getChart(self): return self.parent.chart - + """* Returns the <tt>Curve</tt> that contains this ** <tt>Symbol</tt>. ** @@ -704,7 +704,7 @@ def getChart(self): *""" def getParent(self): return self.parent - + """* ** Returns the value, previously specified via ** <tt>setPieSliceOrientation</tt>, that defines the angular @@ -724,28 +724,28 @@ def getParent(self): """ def getPieSliceOrientation(self): return self.pieSliceOrientation - + # Used internally to translate <tt>Double.NaN</tt> into # an appropriate default slice orientation that, when pie # slice orientation isn't explicitly specified, results # in a series of adjacent slices that will form a pie # when the sum of the slice sizes equals 1.0 - + def getDecodedPieSliceOrientation(self): result = self.pieSliceOrientation if (Double.NaN==(result)): result = self.defaultPieSliceOrientation - + return result - - + + def setDefaultPieSliceOrientation(self, defaultOrientation): self.defaultPieSliceOrientation = defaultOrientation - + def getDefaultPieSliceOrientation(self): return self.defaultPieSliceOrientation - - + + """* ** Returns the value, previously specified via ** <tt>setPieSliceSize</tt>, that defines the size of @@ -764,9 +764,9 @@ def getDefaultPieSliceOrientation(self): """ def getPieSliceSize(self): return self.pieSliceSize - - - + + + """ * Returns the radius of the pie from which this * symbol's pie slice was extracted. @@ -783,22 +783,22 @@ def getPieSliceRadius(self, pp, onY2): spacing = self.getFillSpacing() if 0 == spacing: spacing = 1 - + nBands = int ( round(result/spacing) ) result = nBands * spacing return result - - + + # defines first, second edge angle in standard radian units def getPieSliceTheta0(self): - + result = (0.75 - self.getDecodedPieSliceOrientation())*2*math.pi return result - + def getPieSliceTheta1(self): return self.getPieSliceTheta0() - 2.*math.pi*self.getPieSliceSize() - - + + """* ** Returns this symbol's height as previously set by ** <tt>setModelHeight</tt>. @@ -813,9 +813,9 @@ def getPieSliceTheta1(self): """ def getModelHeight(self): return self.modelHeight - - - + + + """* ** Returns this symbol's width as previously set by ** <tt>setModelWidth</tt>. @@ -830,7 +830,7 @@ def getModelHeight(self): """ def getModelWidth(self): return self.modelWidth - + """* Returns this symbol's type. ** ** @return the type of this symbol. @@ -839,7 +839,7 @@ def getModelWidth(self): *""" def getSymbolType(self): return self.symbolType - + """ * Do points on the curve associated with this symbol * use a horizontal (or vertical) binning strategy for @@ -851,15 +851,15 @@ def isHorizontallyBanded(self): # not fixed by symbol type: use brush shape determined banding # (we are guessing point distribution based on brush shape) result = self.brushHeight < self.brushWidth - + else: result = bool(self.symbolType.isHorizontallyBanded()) - - + + return result - - - + + + """ * If passed an rgba-like string (rgba(255,255,128,0.5)) * returns the collapsed-to-rgb version (rgb(255,255,128)). @@ -883,19 +883,19 @@ def collapseRGBAToRGB(self, rgba): FIRST_PAREN = 4 lastComma = rgba.rfind(",") result = "rgb" + rgba[FIRST_PAREN:lastComma] + ")" - + else: raise IllegalArgumentException( "Your RGBA color specification: '" + rgba + "'" + " was not in the GChart-required form: rgba(Red,Green,Blue,Alpha)" + " where Red, Green and Blue are integers in the range 0 to 255 and" + " Alpha is a double in the range 0.0 to 1.0") - - + + # else special keyword or else some (unchecked) CSS color format return result - - + + """* ** Specifies the background or fill color of this symbol. @@ -914,8 +914,8 @@ def setBackgroundColor(self, backgroundColor): self.backgroundColor = backgroundColor # don't want to keep collapsing whenever we render, so save it: self.backgroundColorCSS = self.collapseRGBAToRGB(backgroundColor) - - + + """* Specifies the baseline value for this symbol. Use a ** baseline value when you need to create bar charts whose ** bars extend up/down to a specified y baseline value (for @@ -938,9 +938,9 @@ def setBackgroundColor(self, backgroundColor): def setBaseline(self, baseline): self.getParent().invalidate() self.baseline = baseline - - - + + + """* ** Specifies the border color, as a CSS or RGBA color ** specification string. @@ -966,8 +966,8 @@ def setBorderColor(self, borderColor): self.getParent().invalidate() self.borderColor = borderColor self.borderColorCSS = self.collapseRGBAToRGB(borderColor) - - + + """* ** Sets the border style of the rectangular elements used ** to render this symbol. @@ -985,7 +985,7 @@ def setBorderColor(self, borderColor): def setBorderStyle(self, borderStyle): self.getParent().invalidate() self.borderStyle = borderStyle - + """* ** Sets the width of the border around the graphical ** element(s) used to render this curve, in pixels. @@ -996,8 +996,8 @@ def setBorderStyle(self, borderStyle): def setBorderWidth(self, borderWidth): self.getParent().invalidate() self.borderWidth = borderWidth - - + + """* * * Sets the height of the rectangular point-selection @@ -1024,8 +1024,8 @@ def setBorderWidth(self, borderWidth): """ def setBrushHeight(self, height): self.brushHeight = height - - + + """* * Sets the location of the brush relative to the mouse * x,y coordinates. @@ -1040,10 +1040,10 @@ def setBrushHeight(self, height): """ def setBrushLocation(self, location): self.brushLocation = location - - - - + + + + """* * * Convenience method equivalent to: @@ -1076,10 +1076,10 @@ def setBrushLocation(self, location): def setBrushSize(self, width, height): self.setBrushWidth(width) self.setBrushHeight(height) - - - - + + + + """* * * Sets the width of the rectangular "brush" that defines how @@ -1102,9 +1102,9 @@ def setBrushSize(self, width, height): """ def setBrushWidth(self, width): self.brushWidth = width - - - + + + """* * * Allows you to change the x,y scale factors that define @@ -1128,8 +1128,8 @@ def setBrushWidth(self, width): def setDistanceMetric(self, xScaleFactor, yScaleFactor): self.xScaleFactor = xScaleFactor self.yScaleFactor = yScaleFactor - - + + """* ** @deprecated ** @@ -1161,8 +1161,8 @@ def setDistanceMetric(self, xScaleFactor, yScaleFactor): *""" def setFillHasHovertext(self, fillHasHovertext): self.fillHasHovertext = fillHasHovertext - - + + """* ** Specifies the spacing between successive rectangular ** elements used to render any required non-rectangular @@ -1189,16 +1189,16 @@ def setFillHasHovertext(self, fillHasHovertext): """ def setFillSpacing(self, fillSpacing): self.getParent().invalidate() - if (not (Double.NaN==(fillSpacing)) and + if (not (Double.NaN==(fillSpacing)) and fillSpacing != 0 and fillSpacing < 1): raise IllegalArgumentException( "fillSpacing="+fillSpacing+"; "+ "fillSpacing must either be >= 1, or else " + "equal to either 0 or Double.NaN.") - + self.fillSpacing = fillSpacing - - + + """* ** Sets the "thickness" of the rectangular elements used to ** render any required non-rectangular features of this symbol. @@ -1225,10 +1225,10 @@ def setFillThickness(self, fillThickness): "fillThickness="+self.fillThickness+"; "+ "fillThickness must either be >= 0, or else " + "equal to GChartConsts.NAI.") - + self.fillThickness = fillThickness - - + + """* * Sets a boolean that determines if point-specific * annotations will popup whenever you hover over a point on @@ -1256,7 +1256,7 @@ def setFillThickness(self, fillThickness): """ def setHoverAnnotationEnabled(self, hoverAnnotationEnabled): self.hoverAnnotationEnabled = hoverAnnotationEnabled - + """* ** Specifies the weight of the font that will be used ** to render the text of this point's hover annotations. @@ -1280,7 +1280,7 @@ def setHoverAnnotationEnabled(self, hoverAnnotationEnabled): *""" def setHoverFontWeight(self, cssWeight): self.getHoverAnnotation().setFontWeight(cssWeight) - + """* ** Specifies the color of the hover annotations' font. ** @@ -1305,9 +1305,9 @@ def setHoverFontWeight(self, cssWeight): *""" def setHoverFontColor(self, cssColor): self.getHoverAnnotation().setFontColor(cssColor) - - - + + + """* ** Specifies the CSS font-style used by this symbol's hover ** annotations. @@ -1326,7 +1326,7 @@ def setHoverFontColor(self, cssColor): *""" def setHoverFontStyle(self, cssStyle): self.getHoverAnnotation().setFontStyle(cssStyle) - + """* ** Specifies the CSS font size used in this symbol's hover ** annotations, in pixels. @@ -1345,7 +1345,7 @@ def setHoverFontStyle(self, cssStyle): *""" def setHoverFontSize(self, fontSize): self.getHoverAnnotation().setFontSize(fontSize) - + """* * * Specifies the location of this point's hover annotations. Set @@ -1403,8 +1403,8 @@ def setHoverFontSize(self, fontSize): """ def setHoverLocation(self, hoverLocation): self.getHoverAnnotation().setLocation(hoverLocation) - - + + """* * * Sets the symbol type that GChart will use when positioning @@ -1468,7 +1468,7 @@ def setHoverLocation(self, hoverLocation): """ def setHoverAnnotationSymbolType(self, hoverAnnotationSymbolType): self.hoverAnnotationSymbolType = hoverAnnotationSymbolType - + """* * Specifies the background color used to indicate that the mouse is * "touching" (hovering over) a point. @@ -1513,7 +1513,7 @@ def setHoverAnnotationSymbolType(self, hoverAnnotationSymbolType): """ def setHoverSelectionBackgroundColor(self, hoverSelectionBackgroundColor): self.hoverSelectionBackgroundColor = hoverSelectionBackgroundColor - + """* * Specifies the border color used to indicate that the mouse is * "touching" (hovering over) a point. @@ -1549,8 +1549,8 @@ def setHoverSelectionBackgroundColor(self, hoverSelectionBackgroundColor): """ def setHoverSelectionBorderColor(self, hoverSelectionBorderColor): self.hoverSelectionBorderColor = hoverSelectionBorderColor - - + + """* * Specifies the border style used to indicate that the mouse is * "touching" (hovering over) a point. @@ -1585,9 +1585,9 @@ def setHoverSelectionBorderColor(self, hoverSelectionBorderColor): """ def setHoverSelectionBorderStyle(self, hoverSelectionBorderStyle): self.hoverSelectionBorderStyle = hoverSelectionBorderStyle - - - + + + """* * Sets the width of the border around the perimeter of * rectangles used to indicate that the mouse is @@ -1622,11 +1622,11 @@ def setHoverSelectionBorderStyle(self, hoverSelectionBorderStyle): """ def setHoverSelectionBorderWidth(self, borderWidth): self.hoverSelectionBorderWidth = borderWidth - - - - - + + + + + """* * Specifies if hover selection feedback will be provided * for this curve. @@ -1662,8 +1662,8 @@ def setHoverSelectionBorderWidth(self, borderWidth): """ def setHoverSelectionEnabled(self, hoverSelectionEnabled): self.hoverSelectionEnabled = hoverSelectionEnabled - - + + """* * Specifies the fill spacing that will be used when * rendering this curve's hover selection feedback. @@ -1682,10 +1682,10 @@ def setHoverSelectionEnabled(self, hoverSelectionEnabled): * @see #setFillSpacing setFillSpacing * """ - + def setHoverSelectionFillSpacing(self, selectionFillSpacing): self.hoverSelectionFillSpacing = selectionFillSpacing - + """* * Specifies the fill thickness that will be used when * rendering this curve's hover selection feedback. @@ -1706,9 +1706,9 @@ def setHoverSelectionFillSpacing(self, selectionFillSpacing): """ def setHoverSelectionFillThickness(self, selectionFillThickness): self.hoverSelectionFillThickness = selectionFillThickness - - - + + + """* * Sets the height of the symbol used to indicate * when a given point is being "hovered over" with the @@ -1739,8 +1739,8 @@ def setHoverSelectionFillThickness(self, selectionFillThickness): """ def setHoverSelectionHeight(self, selectionHeight): self.hoverSelectionHeight = selectionHeight - - + + """* * Specifies the URL that will define the image * used to render selection feedback for points on @@ -1769,7 +1769,7 @@ def setHoverSelectionHeight(self, selectionHeight): * @see #getHoverSelectionImageURL getHoverSelectionImageURL * @see #setImageURL setImageURL * @see #setBlankImageURL setBlankImageURL - + * @param imageURL the url that defines the image used to generate * selection feedback for points rendered with this symbol, or * <tt>None</tt> to to use GChart's default selection image URL (a @@ -1778,8 +1778,8 @@ def setHoverSelectionHeight(self, selectionHeight): """ def setHoverSelectionImageURL(self, imageURL): self.hoverSelectionImageURL = imageURL - - + + """* * * Sets the symbol type that GChart will use when @@ -1833,7 +1833,7 @@ def setHoverSelectionImageURL(self, imageURL): def setHoverSelectionSymbolType(self, hoverSelectionSymbolType): # throwExceptionOnAnchorMouse(hoverSelectionSymbolType) self.hoverSelectionSymbolType = hoverSelectionSymbolType - + """* * Sets the width of the symbol used to indicate * when a given point is being "hovered over" with the @@ -1864,10 +1864,10 @@ def setHoverSelectionSymbolType(self, hoverSelectionSymbolType): """ def setHoverSelectionWidth(self, selectionWidth): self.hoverSelectionWidth = selectionWidth - - - - + + + + """* ** Defines the "hover-text" that appears whenever the user ** points their mouse at a point on the curve. @@ -1891,10 +1891,10 @@ def setHoverSelectionWidth(self, selectionWidth): def setHovertextTemplate(self, hovertextTemplate): if self.hovertextTemplate != hovertextTemplate: self.hovertextChunks = None; # invalidates prev chunk-parse - + self.hovertextTemplate = hovertextTemplate - - + + """* * Specifies a <tt>HoverUpdateable</tt> widget that will be * used to display the hover annotations associated with this @@ -1953,19 +1953,19 @@ def setHovertextTemplate(self, hovertextTemplate): * @see #setHoverYShift setHoverYShift * """ - - + + def setHoverWidget(self, hoverWidget, widthUpperBound=GChartConsts.DEFAULT_WIDGET_WIDTH_UPPERBOUND, heightUpperBound=GChartConsts.DEFAULT_WIDGET_HEIGHT_UPPERBOUND): if None != hoverWidget and not isinstance(hoverWidget, Widget): raise IllegalArgumentException( "hoverWidget must either be None or a Widget.") - + self.getHoverAnnotation().setWidget(hoverWidget, widthUpperBound, heightUpperBound) - - + + """* * Specifies the number of pixels (along the x-axis) to * move this symbol's hover annotations from their default, @@ -1992,8 +1992,8 @@ def setHoverWidget(self, hoverWidget, """ def setHoverXShift(self, xShift): self.getHoverAnnotation().setXShift(xShift) - - + + """* * Specifies the number of pixels (along the y-axis) to * move this symbol's hover annotations from their default, @@ -2020,9 +2020,9 @@ def setHoverXShift(self, xShift): """ def setHoverYShift(self, yShift): self.getHoverAnnotation().setYShift(yShift) - - - + + + """* * Specifies the URL that will define the image * used to represent the points on this curve. @@ -2045,8 +2045,8 @@ def setHoverYShift(self, yShift): """ def setImageURL(self, imageURL): self.imageURL = imageURL - - + + """* ** Sets the height of this symbol (including any specified border) ** in pixels. @@ -2068,7 +2068,7 @@ def setHeight(self, height): self.getParent().invalidate() self.height = height self.modelHeight = Double.NaN - + """* ** Sets the height of this symbol (including any specified border) ** in model units (arbitrary, user-defined, units). Model @@ -2098,7 +2098,7 @@ def setHeight(self, height): def setModelHeight(self, modelHeight): self.getParent().invalidate() self.modelHeight = modelHeight - + """* ** Sets the width of this symbol (including any specified border) ** in model units. Model units are an arbitrary, user-defined @@ -2128,8 +2128,8 @@ def setModelHeight(self, modelHeight): def setModelWidth(self, modelWidth): self.getParent().invalidate() self.modelWidth = modelWidth - - + + """* ** Specifies a value that defines the angular orientation of ** the first edge of the pie slice associated with this @@ -2184,10 +2184,10 @@ def setPieSliceOrientation(self, pieSliceOrientation): "pieSliceOrientation="+str(self.pieSliceOrientation)+"; "+ "pieSliceOrientation must be >=0 and < 1, or else " + "equal to Double.NaN.") - + self.pieSliceOrientation = pieSliceOrientation - - + + """* ** Specifies a value that defines the angular size of ** any pie slice associated with this symbol. @@ -2228,10 +2228,10 @@ def setPieSliceSize(self, pieSliceSize): raise IllegalArgumentException( "pieSliceSize="+self.pieSliceSize+"; the requirement: "+ "0.0 <= pieSliceSize <= 1.0 must be satisfied.") - + self.pieSliceSize = pieSliceSize - - + + """* ** Sets the type of this symbol. ** <p> @@ -2260,9 +2260,9 @@ def setSymbolType(self, symbolType): idx = self.getChart().getCurveIndex(self.getParent()) self.getChart().invalidateDependentSlices(idx) - - - + + + """* ** Sets the width of this symbol (including any specified border) ** in pixels. @@ -2285,9 +2285,9 @@ def setWidth(self, width): self.getParent().invalidate() self.width = width self.modelWidth = Double.NaN - - - + + + """ * Copies properties of the "from" symbol to this symbol. * @@ -2328,30 +2328,30 @@ def copy(self, fc): # unsets the other, etc.). Logic below reflects this. if not Double.NaN==(fc.getModelHeight()): self.setModelHeight(fc.getModelHeight()) - + else: self.setHeight(fc.getHeight()) - + if not Double.NaN==(fc.getModelWidth()): self.setModelWidth(fc.getModelWidth()) - + else: self.setWidth(fc.getWidth()) - - + + self.setPieSliceOrientation(fc.getPieSliceOrientation()) self.setDefaultPieSliceOrientation(fc.getDefaultPieSliceOrientation()) self.setPieSliceSize(fc.getPieSliceSize()) self.setSymbolType(fc.getSymbolType()) - - + + def getAnnotation(self): if self.annotation is None: self.annotation = Annotation() - + return self.annotation - - + + """* ** Returns this symbol's height, as previously set by ** <tt>setHeight</tt>. @@ -2360,23 +2360,23 @@ def getAnnotation(self): ** ** @see #setHeight setHeight """ - + # Pixel height of symbol when rendered on given plot panel def getHeight(self, pp=None, onY2=None): - + if pp is None and onY2 is None: return self.height mH = self.getModelHeight() if (Double.NaN==(mH)): result = self.getHeight() - + else: result = pp.dyToPixel(mH,onY2) - - + + return result - + """* ** Returns this symbol's width ** as previously set by <tt>setWidth</tt>. @@ -2395,26 +2395,26 @@ def getHeight(self, pp=None, onY2=None): ** @see #setWidth setWidth ** @see #setModelWidth setModelWidth """ - - + + # Pixel width of symbol when rendered on given plot panel def getWidth(self, pp=None): - + if pp is None: return self.width mW = self.getModelWidth() if (Double.NaN==(mW)): result = self.getWidth() - + else: result = pp.dxToPixel(mW) - - + + return result - - - + + + """ Renders the symbol at the specified position within the plot panel, by creating appropriately positioned Image and Grid (for any Annotation associated with this symbol @@ -2422,7 +2422,7 @@ def getWidth(self, pp=None): are used to represent: each point on a curve with any associated point annotations, axes, gridlines, ticks and their tick-labels. """ - + def realizeSymbol(self, pp, grp, arp, annotation, onY2, clipPlotArea, clipDecoratedChart, drawMainSymbol, x, y, prevX, prevY, @@ -2434,13 +2434,13 @@ def realizeSymbol(self, pp, grp, arp, annotation, drawMainSymbol, x, y, prevX, prevY, nextX, nextY) - - - - - - - + + + + + + + # end of class Symbol diff --git a/library/pyjamas/chart/SymbolType.py b/library/pyjamas/chart/SymbolType.py index 4f9460ca0..27f202c2a 100644 --- a/library/pyjamas/chart/SymbolType.py +++ b/library/pyjamas/chart/SymbolType.py @@ -187,7 +187,7 @@ def getBrushWidth(self, sym): # symbols are part of the internals of a GChart, # so only we should instantiate them. def __init__(self, widthMultiplier, heightMultiplier, - pixelPadLeft, pixelPadRight, + pixelPadLeft, pixelPadRight, pixelPadTop, pixelPadBottom, isHorizontallyBanded=None): AnnotationLocation.validateMultipliers(widthMultiplier, @@ -1044,7 +1044,7 @@ def realizeOneImageOfSymbol(self, pp, grp, arp, symbol, annotation, onY2, clipPl # if the image has an attached label, realize that if (annotation!=None and (annotation.getText() is not None or - annotation.getWidget() is not None) and + annotation.getWidget() is not None) and annotation.getVisible()): loc = annotation.getLocation() if None == loc: @@ -1915,7 +1915,7 @@ def yWherePieEdgeIntersectsVerticalLine(self, xOfVerticalLine, xPieCenter, yPieC # returns the x coordinate where a pie slice edge # intersects a given horizontal line, or NaN if none. def xWherePieEdgeIntersectsHorizontalLine(self, yOfHorizontalLine, - xPieCenter, yPieCenter, + xPieCenter, yPieCenter, pieRadius, pieEdgeAngle): result = Double.NaN dyToArc = pieRadius*math.sin(pieEdgeAngle) @@ -2115,9 +2115,9 @@ def realizeSymbol(self, pp, grp, arp, symbol, annotation, onY2, clipPlotArea, cl yAxisWidth = pp.getYAxisEnsembleWidth() titleThickness = pp.chartTitleThickness() if not SymbolType.intersects(self, 0.0 - yAxisWidth, - 0.0 - titleThickness, - pp.getXChartSizeDecoratedQuickly()-yAxisWidth, - pp.getYChartSizeDecoratedQuickly()-titleThickness, + 0.0 - titleThickness, + pp.getXChartSizeDecoratedQuickly()-yAxisWidth, + pp.getYChartSizeDecoratedQuickly()-titleThickness, xPx-r, yPx-r, xPx+r, yPx+r): return; # rect containing pie is off decorated chart @@ -2159,7 +2159,7 @@ def realizeSymbol(self, pp, grp, arp, symbol, annotation, onY2, clipPlotArea, cl """ borderWidth = symbol.getBorderWidth() if borderWidth >= 0: - adjustedBorderWidth = borderWidth + adjustedBorderWidth = borderWidth else: adjustedBorderWidth = 2*abs(borderWidth) @@ -2221,16 +2221,16 @@ def realizeSymbol(self, pp, grp, arp, symbol, annotation, onY2, clipPlotArea, cl # non-negative borders fill before stroking (thus # stroke overwrites internal half of border) # GWTCanvas thows an exception w "transparent" - if (borderWidth >= 0 and thickness > 0 and - GChartConsts.TRANSPARENT_BORDER_COLOR != backgroundColor and + if (borderWidth >= 0 and thickness > 0 and + GChartConsts.TRANSPARENT_BORDER_COLOR != backgroundColor and "transparent" != backgroundColor): canvas.setFillStyle(backgroundColor) canvas.fill() # stroke whenever a border is present - if (borderWidth != 0 and - GChartConsts.TRANSPARENT_BORDER_COLOR != borderColor and + if (borderWidth != 0 and + GChartConsts.TRANSPARENT_BORDER_COLOR != borderColor and "transparent" != borderColor): canvas.setStrokeStyle(borderColor) canvas.stroke() @@ -2238,9 +2238,9 @@ def realizeSymbol(self, pp, grp, arp, symbol, annotation, onY2, clipPlotArea, cl # negative borders fill AFTER stroking (thus zapping # the internal half of the stroked border). - if (borderWidth < 0 and - thickness > 0 and - GChartConsts.TRANSPARENT_BORDER_COLOR != backgroundColor and + if (borderWidth < 0 and + thickness > 0 and + GChartConsts.TRANSPARENT_BORDER_COLOR != backgroundColor and "transparent" != backgroundColor): canvas.setFillStyle(backgroundColor) canvas.fill() @@ -2279,9 +2279,9 @@ def realizeSymbol(self, pp, grp, arp, symbol, annotation, onY2, clipPlotArea, cl optimalIsVertical = (sl.yMax - sl.yMin) > (sl.xMax - sl.xMin) isFullPie = (symbol.getPieSliceSize() == 1.0) # perform any vertical shading that may be required: - if (nBands > 0 and - (self.verticallyShaded or - (self.optimallyShaded and + if (nBands > 0 and + (self.verticallyShaded or + (self.optimallyShaded and optimalIsVertical))): for i in range(int(round(nBands*sl.xMin)), int(sl.xMax*nBands)): @@ -2356,7 +2356,7 @@ def realizeSymbol(self, pp, grp, arp, symbol, annotation, onY2, clipPlotArea, cl # ALWAYS rely on the (mathematically correct) # fact that problematic bars always connect p[1] # and p[2]. - if (abs(theta0-theta1) <= math.pi or + if (abs(theta0-theta1) <= math.pi or self.angleInRange(self.angle(xi-xPx, yPx-(0.3*p[j]+0.7*p[j-1])), theta0,theta1)): @@ -2383,8 +2383,8 @@ def realizeSymbol(self, pp, grp, arp, symbol, annotation, onY2, clipPlotArea, cl # Now do any required horizontal shading. This is # basically the same as the code for vertical shading # above (w appropriate transposition/adjustments). - if (nBands > 0 and (self.horizontallyShaded or - (self.optimallyShaded and + if (nBands > 0 and (self.horizontallyShaded or + (self.optimallyShaded and not optimalIsVertical))): for i in range( int ( round(-nBands*sl.yMax)), int ( -nBands * sl.yMin) ): diff --git a/library/pyjamas/chart/TickLocation.py b/library/pyjamas/chart/TickLocation.py index 4937c3c5a..ea895bd3e 100644 --- a/library/pyjamas/chart/TickLocation.py +++ b/library/pyjamas/chart/TickLocation.py @@ -83,7 +83,7 @@ class TickLocation: """ def __init__(self, locationIndex): self.locationIndex = locationIndex - + # symbol type representing ticks on x axes at given position # axisPosition of -1 is x-axis, +1 is x2-axis. # @@ -92,7 +92,7 @@ def getXAxisSymbolType(self, axisPosition): symbolMap = [SymbolType.BOX_NORTH, SymbolType.BOX_CENTER, SymbolType.BOX_SOUTH] result = symbolMap[axisPosition*self.locationIndex+1] return result - + # symbol type representing ticks on y axes at given position # axisPosition of -1 is y-axis, +1 is y2-axis # @@ -101,8 +101,8 @@ def getYAxisSymbolType(self, axisPosition): symbolMap = [SymbolType.BOX_EAST, SymbolType.BOX_CENTER, SymbolType.BOX_WEST] result = symbolMap[axisPosition*self.locationIndex+1] return result - - + + # class TickLocation """* diff --git a/library/pyjamas/chart/TouchedPointUpdateOption.py b/library/pyjamas/chart/TouchedPointUpdateOption.py index 26b3d948e..5d6cb1efc 100644 --- a/library/pyjamas/chart/TouchedPointUpdateOption.py +++ b/library/pyjamas/chart/TouchedPointUpdateOption.py @@ -30,7 +30,7 @@ class TouchedPointUpdateOption(object): def __init__(self): pass - + """* * When this option is passed to the update method, any * touched point is cleared as a consequence of the update. diff --git a/library/pyjamas/django/Form.py b/library/pyjamas/django/Form.py index 240015cb2..8e35d27f8 100644 --- a/library/pyjamas/django/Form.py +++ b/library/pyjamas/django/Form.py @@ -176,7 +176,7 @@ def save_respond(self, response): for l in self.describe_listeners: l.onSaveDone(self, response) - + def formsetup(self, data=None): if data is None: @@ -188,7 +188,7 @@ def clear_errors(self): for idx, fname in enumerate(self.fields): self.grid.setHTML(idx, 2, None) - + def set_errors(self, errors): offsets = {} @@ -198,7 +198,7 @@ def set_errors(self, errors): err = "<br />".join(err) idx = offsets[k] self.grid.setHTML(idx, 2, err) - + def update_values(self, data = None): if data is not None: self.data = data diff --git a/library/pyjamas/gears/GearsException.py b/library/pyjamas/gears/GearsException.py index 12089c32a..9944b038c 100644 --- a/library/pyjamas/gears/GearsException.py +++ b/library/pyjamas/gears/GearsException.py @@ -26,8 +26,8 @@ class GearsException(Exception): """ def __init__(self, message): super(message) - - + + """* * Creates a exception with the indicated root cause. * @@ -36,6 +36,6 @@ def __init__(self, message): """ def __init__(self, message, cause): super(message, cause) - + diff --git a/library/pyjamas/gears/database/Database.py b/library/pyjamas/gears/database/Database.py index 5a0dbc905..0b501c56c 100644 --- a/library/pyjamas/gears/database/Database.py +++ b/library/pyjamas/gears/database/Database.py @@ -49,7 +49,7 @@ def close(self): self.uncheckedClose() #except ex: # raise DatabaseException(ex.getDescription(), ex) - + """* * Executes the specified SQL statement and returns a {@link ResultSet} * containing the results. diff --git a/library/pyjamas/gears/database/DatabaseException.py b/library/pyjamas/gears/database/DatabaseException.py index 468d1f17e..bf72c8149 100644 --- a/library/pyjamas/gears/database/DatabaseException.py +++ b/library/pyjamas/gears/database/DatabaseException.py @@ -28,8 +28,8 @@ class DatabaseException(GearsException): """ def __init__(self, message): super(message) - - + + """* * Constructor taking a message and root cause. * @@ -38,6 +38,6 @@ def __init__(self, message): """ def __init__(self, message, cause): super(message, cause) - + diff --git a/library/pyjamas/gmaps/Polygon.py b/library/pyjamas/gmaps/Polygon.py index f49ccb176..8fb59eea7 100644 --- a/library/pyjamas/gmaps/Polygon.py +++ b/library/pyjamas/gmaps/Polygon.py @@ -26,14 +26,14 @@ def PolygonOptions(adict): try: if isinstance(adict["paths"], (list,tuple)): adict["paths"] = listToJs(adict["paths"]) - elif isinstance(adict["paths"], basestring): #Gmaps + elif isinstance(adict["paths"], basestring): #Gmaps adict["paths"] = decodePoly(adict["paths"]) - except: #isinstance throws exception for raw javascript objects. + except: #isinstance throws exception for raw javascript objects. pass #That means it's already good. return dictToJs(adict) - + def decodePoly(poly): - """Quickly decodes a gmaps api v2 encoded polyline... deprecated by google but still + """Quickly decodes a gmaps api v2 encoded polyline... deprecated by google but still a good over-the-wire compression format""" JS(""" var i=-1,j=-1,k,l,q=@{{poly}}.match(/[\_-\~]*[\?-\^]/g),w=0,x=0,y=0,z=1e-5; diff --git a/library/pyjamas/gmaps/Utils.py b/library/pyjamas/gmaps/Utils.py index be17cbfd2..71de43613 100644 --- a/library/pyjamas/gmaps/Utils.py +++ b/library/pyjamas/gmaps/Utils.py @@ -48,7 +48,7 @@ def translateGmapsObject(obj, fieldName, fields, pyToJs): if (@{{action}} == 'd') { //console.log("is dict") - // this newobj can be used in js and also in python, + // this newobj can be used in js and also in python, // like this "newobj.field" var newobj = {} for (var i in @{{obj}}) diff --git a/library/pyjamas/locale.py b/library/pyjamas/locale.py index add6fc6a4..146df481f 100644 --- a/library/pyjamas/locale.py +++ b/library/pyjamas/locale.py @@ -1,28 +1,27 @@ #encoding: utf8 """ (C) 2012 by Maho (?ukasz Mach) - + License: GPL - - + + Poor man's i18n support for Pyjamas. - + _("identifier") returns you translated version of "identifier". If you want original (English) version, just do nothing. If you want other language (eg. PL), please import translation_pl in your project, when it's content is: - + from pyjamas.locale import msgs - + msgs["Week"] = "Tydzień" msgs["Jan"] = "Sty" msgs["January"] = "Styczeń" msgs["Other eng identifier you'd like to translate"] = "Inny ang. identyfikator który chciałbyś przetłumaczyć" - + """ msgs = {} def _(identifier): return msgs.get(identifier,identifier) - \ No newline at end of file diff --git a/library/pyjamas/media/Audio.py b/library/pyjamas/media/Audio.py index 82653c911..da91779ff 100644 --- a/library/pyjamas/media/Audio.py +++ b/library/pyjamas/media/Audio.py @@ -21,11 +21,11 @@ * An HTML5 AUDIO element """ class Audio(Media): - + def __init__(self, src=None, **kwargs): self.setElement(DOM.createElement("audio")) if src: self.setSrc(src) - + Media.__init__(self, **kwargs) diff --git a/library/pyjamas/media/Media.ie6.py b/library/pyjamas/media/Media.ie6.py index a754339e7..484df21fa 100644 --- a/library/pyjamas/media/Media.ie6.py +++ b/library/pyjamas/media/Media.ie6.py @@ -26,7 +26,7 @@ def setLoop(self, autorewind): print "autorewind", autorewind self.loopparam = DOM.createElement("PARAM") DOM.setAttribute(self.loopparam, "name", "autorewind") - DOM.setBooleanAttribute(self.loopparam, "VALUE", + DOM.setBooleanAttribute(self.loopparam, "VALUE", autorewind and "true" or "false") self.getElement().appendChild(self.loopparam) @@ -34,7 +34,7 @@ def setAutoplay(self, autostart): print "autoplay", autostart self.playparam = DOM.createElement("PARAM") DOM.setAttribute(self.playparam, "name", "autostart") - DOM.setBooleanAttribute(self.playparam, "VALUE", + DOM.setBooleanAttribute(self.playparam, "VALUE", autostart and "true" or "false") self.getElement().appendChild(self.playparam) diff --git a/library/pyjamas/media/Media.py b/library/pyjamas/media/Media.py index b9922244a..1a82e38cd 100644 --- a/library/pyjamas/media/Media.py +++ b/library/pyjamas/media/Media.py @@ -63,16 +63,16 @@ class Media(Widget): HasStalledHandlers, HasSuspendHandlers, HasTimeUpdateHandlers, HasVolumeChangeHandlers, HasWaitingHandlers, HasAllMouseHandlers, HasClickHandlers""" - + def __init__(self, **kwargs): self.mediaEventsToSink = 0 self.mediaEventsInitialized = False - + Widget.__init__(self, **kwargs) - + def setSrc(self, src): DOM.setAttribute(self.getElement(), 'src', src) - + def addSrc(self, src): s = DOM.createElement("source") DOM.setAttribute(s, 'src', src) @@ -90,53 +90,53 @@ def getCurrentSrc(self): def getCurrentTime(self): return self.getElement().currentTime - + def setCurrentTime(self, time): self.getElement().currentTime = time - + def getStartTime(self): return self.getElement().startTime - + def getDuration(self): return self.getElement().duration - + def isPaused(self): return self.getElement().paused - + def getDefaultPlaybackRate(self): return self.getElement().defaultPlaybackRate - + def setDefaultPlaybackRate(self, rate): self.getElement().defaultPlaybackRate = rate - + def getPlaybackRate(self): return self.getElement().playbackRate - + def setPlaybackRate(self, rate): self.getElement().playbackRate = rate - + def getPlayed(self): return self.getElement().played - + def getSeekable(self): return self.getElement().seekable - + def hasEnded(self): return self.getElement().ended - + def isLoop(self): return bool(self.getElement().loop) - + def getVolume(self): return self.getElement().volume - + def setVolume(self, volume): self.getElement().volume = volume - + def getReadyState(self): return self.getElement().readyState - - + + """* * If set, this informs the browser that the media element is likely to be * played and that it should begin buffering the content immediately. @@ -149,8 +149,8 @@ def getReadyState(self): """ def setAutobuffer(self, autobuffer): self.getElement().autobuffer = autobuffer - - + + """* * Whether to automatically begin playback of the media resource as soon as * it's possible to do so without stopping. @@ -159,8 +159,8 @@ def setAutobuffer(self, autobuffer): """ def setAutoplay(self, autoplay): self.getElement().autoplay = autoplay - - + + """* * Whether the media element is to seek back to the start of the media * resource upon reaching the end. @@ -169,8 +169,8 @@ def setAutoplay(self, autoplay): """ def setLoop(self, loop): self.getElement().loop = loop - - + + """* * Whether the browser should expose a user interface to the user. This user * interface should include features to begin playback, pause playback, seek @@ -183,38 +183,38 @@ def setLoop(self, loop): """ def setControls(self, controls): DOM.setBooleanAttribute(self.getElement(), "controls", controls) - + def hasControls(self): DOM.getBooleanAttribute(self.getElement(), "controls") - + def isMuted(self): return self.getElement().muted - + def play(self): self.getElement().play() - + def load(self): self.getElement().load() - + def pause(self): self.getElement().pause() - + def canPlayType(self, etype): self.getElement().canPlayType(etype) def setMute(self, muted): self.getElement().setMute(muted) - - + + """* * Adds a handler to be called when the user agent stops fetching the media data before it is * completely downloaded, but not due to an error. """ - + def addAbortHandler(self, handler): return self.addMediaEventHandler(handler, AbortEvent.getType()) - - + + """* * Adds a handler to be called when the user agent can resume playback of the media data, but * estimates that if playback were to be started now, the media resource could @@ -223,11 +223,11 @@ def addAbortHandler(self, handler): * * @param handler the {@link CanPlayHandler} to be called """ - + def addCanPlayHandler(self, handler): return self.addMediaEventHandler(handler, CanPlayEvent.getType()) - - + + """* * Adds a handler to be called when the user agent estimates that if playback were to be started * now, the media resource could be rendered at the current playback rate all @@ -235,26 +235,26 @@ def addCanPlayHandler(self, handler): * * @param handler the {@link CanPlayThroughHandler} to be called """ - + def addCanPlayThroughHandler(self, handler): return self.addMediaEventHandler(handler, CanPlayThroughEvent.getType()) - - - + + + def addDurationChangeHandle(self, handler): return self.addMediaEventHandler(handler, DurationChangeEvent.getType()) - - + + """* * Adds a handler to be called when the duration attribute has just been updated. * * @param handler the {@link DurationChangeHandler} to be called """ - + def addEmptiedHandler(self, handler): return self.addMediaEventHandler(handler, EmptiedEvent.getType()) - - + + """* * Adds a handler to be called when a media element whose networkState was previously not in the * NETWORK_EMPTY state has just switched to that state (either because of a @@ -265,199 +265,199 @@ def addEmptiedHandler(self, handler): * * @param handler the {@link EmptiedHandler} to be called """ - + def addEndedHandler(self, handler): return self.addMediaEventHandler(handler, EndedEvent.getType()) - - + + """* * Adds a handler to be called when playback has stopped because the end of the media resource was * reached. * * @param handler the {@link EndedHandler} to be called """ - + def addErrorHandler(self, handler): return self.addMediaEventHandler(handler, ErrorEvent.getType()) - - + + """* * Adds a handler to be called when the user agent begins looking for media data, as part of the * resource selection algorithm. * * @param handler the {@link LoadStartHandler} to be called """ - + def addLoadStartHandler(self, handler): return self.addMediaEventHandler(handler, LoadStartEvent.getType()) - - + + """* * Adds a handler to be called when the user agent can render the media data at the current * playback position for the first time. * * @param handler the {@link LoadedDataHandler} to be called """ - + def addLoadedDataHandler(self, handler): return self.addMediaEventHandler(handler, LoadedDataEvent.getType()) - - + + """* * Adds a handler to be called when the user agent has just determined the duration and dimensions * of the media resource. * * @param handler the {@link LoadedMetadataHandler} to be called """ - + def addLoadedMetadataHandler(self, handler): return self.addMediaEventHandler(handler, LoadedMetadataEvent.getType()) - - + + """* * Adds a handler to be called when playback has been paused. Fired after the pause method has * returned. * * @param handler the {@link PauseHandler} to be called """ - + def addPauseHandler(self, handler): return self.addMediaEventHandler(handler, PauseEvent.getType()) - - + + """* * Adds a handler to be called when playback has begun. Fired after the play() method has returned. * * @param handler the {@link PlayHandler} to be called """ - + def addPlayHandler(self, handler): return self.addMediaEventHandler(handler, PlayEvent.getType()) - - + + """* * Adds a handler to be called when playback has started. * * @param handler the {@link PlayingHandler} to be called """ - + def addPlayingHandler(self, handler): return self.addMediaEventHandler(handler, PlayingEvent.getType()) - - + + """* * Adds a handler to be called when the user agent is fetching media data. * * @param handler the {@link ProgressHandler} to be called """ - + def addProgressHandler(self, handler): return self.addMediaEventHandler(handler, ProgressEvent.getType()) - - + + """* * Adds a handler to be called when either the defaultPlaybackRate or the playbackRate attribute * has just been updated. * * @param handler the {@link RateChangeHandler} to be called """ - + def addRateChangeHandler(self, handler): return self.addMediaEventHandler(handler, RateChangeEvent.getType()) - - + + """* * Adds a handler to be called when a seek operation has completed. * * @param handler the {@link SeekedHandler} to be called """ - + def addSeekedHandler(self, handler): return self.addMediaEventHandler(handler, SeekedEvent.getType()) - - + + """* * Adds a handler to be called when the user agent is seeking to a time position in the stream. * * @param handler the {@link SeekingHandler} to be called """ - + def addSeekingHandler(self, handler): return self.addMediaEventHandler(handler, SeekingEvent.getType()) - - + + """* * Adds a handler to be called when the user agent is trying to fetch media data, but data is * unexpectedly not forthcoming. * * @param handler the {@link StalledHandler} to be called """ - + def addStalledHandler(self, handler): return self.addMediaEventHandler(handler, StalledEvent.getType()) - - + + """* * Adds a handler to be called when the user agent is intentionally not currently fetching media * data, but does not have the entire media resource downloaded. * * @param handler the {@link SuspendHandler} to be called """ - + def addSuspendHandler(self, handler): return self.addMediaEventHandler(handler, SuspendEvent.getType()) - - + + """* * Adds a handler to be called when the current playback position changed as part of normal * playback or in an especially interesting way, for example discontinuously. * * @param handler the {@link TimeUpdateHandler} to be called """ - + def addTimeUpdateHandler(self, handler): return self.addMediaEventHandler(handler, TimeUpdateEvent.getType()) - - + + """* * Adds a handler to be called when either the volume attribute or the muted attribute has changed. * Fired after the relevant attribute's setter has returned. * * @param handler the {@link VolumeChangeHandler} to be called """ - + def addVolumeChangeHandler(self, handler): return self.addMediaEventHandler(handler, VolumeChangeEvent.getType()) - - + + """* * Adds a handler to be called when playback has stopped because the next frame is not available, * but the user agent expects that frame to become available in due course. * * @param handler the {@link WaitingHandler} to be called """ - + def addWaitingHandler(self, handler): return self.addMediaEventHandler(handler, WaitingEvent.getType()) - - + + def addMediaEventHandler(self, handler, etype): assert handler is not None, "handler must not be None" assert etype is not None, "type must not be None" self.maybeInitMediaEvents() self.sinkMediaEvents(mediaEventGetTypeInt(etype.getName())) return addHandler(handler, etype) - - - + + + def sinkMediaEvents(self, eventBitsToAdd): if self.isOrWasAttached(): self.nativeSinkMediaEvents(self.getElement(), eventBitsToAdd) else: self.mediaEventsToSink |= eventBitsToAdd - - - + + + """* * doAttachChildren is called immediately after sinkEvents is called in * Widget. This opportunity is taken to lazily attach event handlers to the @@ -468,14 +468,14 @@ def doAttachChildren(self): self.mediaEventsToSink = -1 if bitsToAdd > 0: self.nativeSinkMediaEvents(self.getElement(), bitsToAdd) - - + + def nativeSinkMediaEvents(self, elem, bits): # chMask = (elem.__mediaEventBits or 0) ^ bits # elem.__mediaEventBits = bits; # if not chMask: # return -# +# # if (chMask & 0x00001) and (bits & 0x00001): # elem.addEventListener('abort', mediaDispatchEvent, false) # else: @@ -565,48 +565,48 @@ def nativeSinkMediaEvents(self, elem, bits): # else: # elem.removeEventListener('waiting', mediaDispatchEvent, false) return - + def addMouseDownHandler(self, handler): return addDomHandler(handler, MouseDownEvent.getType()) - - - + + + def addMouseUpHandler(self, handler): return addDomHandler(handler, MouseUpEvent.getType()) - - - + + + def addMouseOutHandler(self, handler): return addDomHandler(handler, MouseOutEvent.getType()) - - - + + + def addMouseOverHandler(self, handler): return addDomHandler(handler, MouseOverEvent.getType()) - - - + + + def addMouseMoveHandler(self, handler): return addDomHandler(handler, MouseMoveEvent.getType()) - - - + + + def addMouseWheelHandler(self, handler): return addDomHandler(handler, MouseWheelEvent.getType()) - - - + + + def addClickHandler(self, handler): return addDomHandler(handler, ClickEvent.getType()) - - + + def maybeInitMediaEvents(self): if not mediaEventsInitialized: initMediaEvents() mediaEventsInitialized = True - - - + + + """* * Warning: W3C/Standards version """ @@ -620,8 +620,8 @@ def initMediaEvents(self): } } """) - - + + """* * Dispatches an event to the listener. This bypasses the main GWT event * handling system because it's not possible to access from external packages. @@ -639,6 +639,6 @@ def initMediaEvents(self): def dispatchMediaEvent(self, evt, listener): # Pass the event to the listener. listener.onBrowserEvent(evt) - + diff --git a/library/pyjamas/media/MediaElement.py b/library/pyjamas/media/MediaElement.py index 7567b7740..dd2a1aa94 100644 --- a/library/pyjamas/media/MediaElement.py +++ b/library/pyjamas/media/MediaElement.py @@ -18,35 +18,35 @@ class MediaElement(Element): - + def __init__(self): pass - - + + def getNetworkState(self): JS(""" return this.networkState; """) - - + + def getBuffered(self): JS(""" return this.buffered; """) - - + + def isSeeking(self): JS(""" return media.seeking; """) - - + + def setBooleanAttr(self, name, value): if value: setAttribute(name, "") - + else: removeAttribute(name) - - + + diff --git a/library/pyjamas/media/MediaError.py b/library/pyjamas/media/MediaError.py index 6542b8fa2..31e824945 100644 --- a/library/pyjamas/media/MediaError.py +++ b/library/pyjamas/media/MediaError.py @@ -22,11 +22,11 @@ MEDIA_ERR_SRC_NOT_SUPPORTED = 4 class MediaError(object): - + def getCode(self): JS(""" return this.code; """) - + diff --git a/library/pyjamas/media/TimeRanges.py b/library/pyjamas/media/TimeRanges.py index b0449be9f..ed5bfa4d2 100644 --- a/library/pyjamas/media/TimeRanges.py +++ b/library/pyjamas/media/TimeRanges.py @@ -18,22 +18,22 @@ class TimeRanges(object): - + def length(self): JS(""" return this.length; """) - - + + def start(self, index): JS(""" return this.start(index); """) - - + + def end(self, index): JS(""" return this.end(index); """) - + diff --git a/library/pyjamas/media/Video.py b/library/pyjamas/media/Video.py index fc5cd173d..a47174ae4 100644 --- a/library/pyjamas/media/Video.py +++ b/library/pyjamas/media/Video.py @@ -22,7 +22,7 @@ * An HTML5 VIDEO element """ class Video(Media): - + def __init__(self, src=None, **kwargs): self.setElement(DOM.createElement("video")) if src: @@ -32,10 +32,10 @@ def __init__(self, src=None, **kwargs): def getVideoWidth(self): return self.getElement().videoWidth - + def getVideoHeight(self): return self.getElement().videoHeight - + def setPoster(self, url): self.getElement().poster = url diff --git a/library/pyjamas/media/VideoElement.py b/library/pyjamas/media/VideoElement.py index af9fa5a2a..a3010fe81 100644 --- a/library/pyjamas/media/VideoElement.py +++ b/library/pyjamas/media/VideoElement.py @@ -17,57 +17,57 @@ @TagName(VideoElement.TAG) class VideoElement(MediaElement): TAG = "video" - + def create(self): return Document.get().createElement(TAG).cast() - - + + def __init__(self): pass - - + + def getWidth(self): JS(""" return this.width; """) - - + + def setWidth(self, width): JS(""" this.width = width; """) - - + + def getHeight(self): JS(""" return this.height; """) - - + + def setHeight(self, height): JS(""" this.height = height; """) - - + + def getVideoWidth(self): JS(""" return this.videoWidth; """) - - + + def getVideoHeight(self): JS(""" return this.videoHeight; """) - - + + def getPoster(self): JS(""" return this.poster; """) - - + + def setPoster(self, url): JS(""" this.poster = url; diff --git a/library/pyjamas/raphael/raphael.py b/library/pyjamas/raphael/raphael.py index e57e2b451..3a87bb6f4 100644 --- a/library/pyjamas/raphael/raphael.py +++ b/library/pyjamas/raphael/raphael.py @@ -52,10 +52,10 @@ def __init__(self,element): onMouseEnter = getattr(self, "_onMouseEnter") onMouseLeave = getattr(self, "_onMouseLeave") onMouseOut = getattr(self, "_onMouseOut") - onDblClick = getattr(self, "_onDblClick") + onDblClick = getattr(self, "_onDblClick") onContextMenu = getattr(self, "_onContextMenu") JS(""" - this._event_element=@{{element}}; + this._event_element=@{{element}}; this._event_element.onclick = @{{onClick}}; this._event_element.onmousedown = @{{onMouseDown}}; this._event_element.onmouseup = @{{onMouseUp}}; @@ -65,8 +65,8 @@ def __init__(self,element): this._event_element.onmouseleave = @{{onMouseLeave}}; this._event_element.ondblclick = @{{onDblClick}}; this._event_element.oncontextmenu= @{{onContextMenu}}; - """) - + """) + def addListener(self, type, listener, sender=None): """ Add a listener function to this element. @@ -102,8 +102,8 @@ def removeListener(self, type, listener): i=self._listeners[type].index(listener) self._sender[type].delete(i) - self._listeners[type].remove(listener) - + self._listeners[type].remove(listener) + def _onClick(self, event): """ Respond to a mouse-click event. """ @@ -164,7 +164,7 @@ def _onMouseOut(self, event): sender = self._sender['mouseout'] for listener,send in zip(listeners,sender): listener(send or self, event) - + def _onDblClick(self, event): """ Respond to a Double Click event. """ @@ -172,7 +172,7 @@ def _onDblClick(self, event): sender = self._sender['mouseout'] for listener,send in zip(listeners,sender): listener(send or self, event) - + def _onContextMenu(self,event): """ Respond to a Context Menue event. """ @@ -181,7 +181,7 @@ def _onContextMenu(self,event): for listener,send in zip(listeners,sender): listener(send or self, event) - + class Raphael(Widget,RaphaelEventHandler): """ A Pyjamas wrapper around the Raphael canvas object. """ @@ -352,12 +352,12 @@ def path(self, data=None, attrs=None,): this._element.attr(@{{attr}}, @{{value}}); """) return RaphaelPathElement(self._element) - + def connection(self,obj1,obj2=None,line=None,bg=None,cp1=None,cp2=None,p1=None,p2=None): line_path=self.path(None,{'stroke-width':5}) bg_path=self.path(None,{'stroke-width':5}) return RaphaelConnectionElement(line_path,bg_path,obj1,obj2,line,bg,cp1,cp2,p1,p2) - + class RaphaelElement(object,RaphaelEventHandler): @@ -638,7 +638,7 @@ def insertAfter(self, element): JS(""" this._element.insertAfter(@{{otherElement}}); """) - + def drag(self,move,start,up): onMove = getattr(self, "_onMove") onStart = getattr(self, "_onStart") @@ -667,13 +667,13 @@ class RaphaelSetElement(RaphaelElement): """ def __init__(self, raphaelElement): - """ - Needs a custom init, since the event handling does not work on set - (since no element is created for Set) + """ + Needs a custom init, since the event handling does not work on set + (since no element is created for Set) """ self._element = raphaelElement self.raphael_elements=[] - + def add(self, element): """ Add an element to this set. """ @@ -687,10 +687,10 @@ def addListener(self,type,listener): for element in self.raphael_elements: element.addListener(type,listener,self) - + def removeListener(self,type,listener): for element in self.raphael_elements: - element.removeListener(type,listener) + element.removeListener(type,listener) ############################################################################# @@ -712,7 +712,7 @@ class RaphaelConnectionElement(RaphaelElement): ''' The connection logic is taken from the Graffle Example at the Raphael Examples ''' - + def __init__(self,line_path, bg_path,obj1=None,obj2=None, line={},bg={}, cp1=None, cp2=None,p1=None,p2=None): self.obj1=obj1 self.obj2=obj2 @@ -721,32 +721,32 @@ def __init__(self,line_path, bg_path,obj1=None,obj2=None, line={},bg={}, cp1=Non self.cp1=cp1 self.cp2=cp2 self.p1=p1 - self.p2=p2 - + self.p2=p2 + self.draw() - + line=line or {} bg=bg or {} if line: self.setLineAttrs(line) if bg: self.setBackGroundAttrs(bg) - - - + + + def _getPath(self): p=[] d={} - dis=[] + dis=[] #cp_map={0:0,90:3,180:1,270:2} - #counter_map={0:1,1:0,2:3,3:2} + #counter_map={0:1,1:0,2:3,3:2} if self.obj1 and self.obj2: bb1=self.obj1.getBBox() bb2=self.obj2.getBBox() p=[ {'x':bb1['x']+bb1['width']/2,'y':bb1['y']-1}, #0: object 1, Top,Middle {'x':bb1['x']+bb1['width']/2,'y':bb1['y']+bb1['height']+1}, #1: object 1, Bottom,Middle {'x':bb1['x']-1, 'y':bb1['y']+bb1['height']/2}, #2: object 1, Left, Middle - {'x':bb1['x']+bb1['width']+1,'y':bb1['y']+bb1['height']/2}, #3: object 1, Right, Middle + {'x':bb1['x']+bb1['width']+1,'y':bb1['y']+bb1['height']/2}, #3: object 1, Right, Middle {'x':bb2['x']+bb2['width']/2,'y':bb2['y']-1}, #4/0:object 2, Top, Middle {'x':bb2['x']+bb2['width']/2,'y':bb2['y']+bb2['height']+1}, #5/1:object 2, Bottom, Middle {'x':bb2['x']-1, 'y':bb2['y']+bb2['height']/2}, #6/2:object 2, Left, Middle @@ -757,10 +757,10 @@ def _getPath(self): p=[ {'x':bb1['x']+bb1['width']/2,'y':bb1['y']-1}, #0: object 1, Top,Middle {'x':bb1['x']+bb1['width']/2,'y':bb1['y']+bb1['height']+1}, #1: object 1, Bottom,Middle {'x':bb1['x']-1, 'y':bb1['y']+bb1['height']/2}, #2: object 1, Left, Middle - {'x':bb1['x']+bb1['width']+1,'y':bb1['y']+bb1['height']/2}]#3: object 1, Right, Middle + {'x':bb1['x']+bb1['width']+1,'y':bb1['y']+bb1['height']/2}]#3: object 1, Right, Middle if not self.obj1 and self.obj2: - bb2=self.obj2.getBBox() + bb2=self.obj2.getBBox() p=[ {'x':bb2['x']+bb2['width']/2,'y':bb2['y']-1}, #4/0:object 2, Top, Middle {'x':bb2['x']+bb2['width']/2,'y':bb2['y']+bb2['height']+1}, #5/1:object 2, Bottom, Middle {'x':bb2['x']-1, 'y':bb2['y']+bb2['height']/2}, #6/2:object 2, Left, Middle @@ -773,7 +773,7 @@ def _getPath(self): if ((i==j-4) or (((i<>3 and j<>6) or p[i]['x'] < p[j]['x']) and ((i<>2 and j<>7) or p[i]['x'] > p[j]['x']) and ((i<>0 and j<>5) or p[i]['y'] > p[j]['y']) and ((i<>1 and j<>4) or p[i]['y'] < p[j]['y'] ))): dis.append(dy+dy) d[dis[len(dis)-1]]=[i,j] - + if len(dis)==0: res=[0,4] else: @@ -785,13 +785,13 @@ def _getPath(self): else: if self.cp1: x1,y1=p[self.cp1]['x'],p[self.cp1]['y'] - res1=self.cp1 + res1=self.cp1 else: x1=self.p1[0] y1=self.p1[1] res1=None if self.cp2: - x4,y4=p[self.cp2+4]['x'],p[self.cp2+4]['y'] + x4,y4=p[self.cp2+4]['x'],p[self.cp2+4]['y'] res2=self.cp2+4 else: x4=self.p2[0] @@ -803,12 +803,12 @@ def _getPath(self): elif res1<>None and res2==None: if res1<4: res2=COUNTER_MAP[res1]+4 - else: + else: res2=COUNTER_MAP[res1]-4 elif res1==None and res2<>None: if res2<4: res1=COUNTER_MAP[res2]+4 - else: + else: res1=COUNTER_MAP[res2]-4 res=[res1,res2] dx=max(abs(x1-x4)/2,10) @@ -816,45 +816,45 @@ def _getPath(self): x2=[x1,x1,x1-dx,x1+dx][res[0]] y2=[y1-dy,y1+dy,y1,y1][res[0]] x3=[0,0,0,0,x4,x4,x4-dx,x4+dx][res[1]] - y3=[0,0,0,0,y1+dy,y1-dy,y4,y4][res[1]] + y3=[0,0,0,0,y1+dy,y1-dy,y4,y4][res[1]] return ','.join(['M',str(x1),str(y1),'C',str(x2),str(y2),str(x3),str(y3),str(x4),str(y4)]) def draw(self,p1=None,p2=None): - self.p1=p1 or self.p1 - self.p2=p2 or self.p2 + self.p1=p1 or self.p1 + self.p2=p2 or self.p2 path=self._getPath() self.line_path.setAttr('path',path) - self.bg_path.setAttr('path',path) + self.bg_path.setAttr('path',path) def setLineAttrs(self,attrs): - self.line_path.setAttrs(attrs) - + self.line_path.setAttrs(attrs) + def setBackGroundAttrs(self,attrs): - self.bg_path.setAttrs(attrs) + self.bg_path.setAttrs(attrs) def toFront(self): self.line_path.toFront() self.bg_path.toFront() - + def toBack(self): self.line_path.toBack() self.bg_path.toBack() - + def remove(self): self.line_path.remove() self.bg_path.remove() - + def addListener(self,type,listener): self.line_path.addListener(type,listener,self) - self.bg_path.addListener(type,listener,self) + self.bg_path.addListener(type,listener,self) def removeListener(self,type,listener): self.line_path.removeListener(type,listener) self.bg_path.removeListener(type,listener) ########################################################################### - + class RaphaelPathElement(RaphaelElement): """ A RaphaelElement that represents a path. @@ -971,4 +971,4 @@ class RaphaelPathElement(RaphaelElement): ## return self - + diff --git a/library/pyjamas/selection/HtmlBBox.py b/library/pyjamas/selection/HtmlBBox.py index 8663e8eda..72eaf405d 100644 --- a/library/pyjamas/selection/HtmlBBox.py +++ b/library/pyjamas/selection/HtmlBBox.py @@ -29,11 +29,11 @@ """ class HtmlBBox: int self.m_x, self.m_y, self.m_width, self.m_height - + def __init__(self, x, y, width, height): """ Create a bounding box based on x/y and width/height - + @param x @param y @param width @@ -43,22 +43,22 @@ def __init__(self, x, y, width, height): self.m_y = y self.m_width = width self.m_height = height - - + + def __init__(self, ele): """ Create a location based on an element's bounding box - + @param ele Element to initialize bounding box with """ this(ele.getAbsoluteLeft(), ele.getAbsoluteTop(), ele.getOffsetWidth(), ele.getOffsetHeight()) - - + + def expand(self, bb): """ Expand this box by the given bounding box - + @param bb box to use to expand this one """ if bb is not None: @@ -67,52 +67,52 @@ def expand(self, bb): self.m_width = Math.max(getAbsoluteRight(), bb.getAbsoluteRight()) - self.m_x self.m_height = Math.max(getAbsoluteBottom(), bb.getAbsoluteBottom()) - self.m_y - - - + + + def getBoundingBox(self, ele): """ Create a bounding box the size of the given element - + @param ele Element to create bounding box around @return a bounding box """ return HtmlBBox(ele) - - + + def getBoundingBox(self, rng): """ Create a bounding box the size of the given range - + @param range Range to create bounding box around @return a bounding box """ HtmlBBox res - + if rng.getStartPoint().getTextNode() == rng.getEndPoint().getTextNode(): res = getBoundingBox(rng.getStartPoint().getTextNode(), rng.getStartPoint().getOffset(), rng.getEndPoint().getOffset()) - + else: res = getBoundingBox(rng.getStartPoint(), True) res.expand(getBoundingBox(rng.getEndPoint(), False)) - + # Make sure the range encompasses all of the text nodes within # the range as well List<Text> texts = rng.getSelectedTextElements() for int i = 1; i < (texts.size() - 1); i++: res.expand(getBoundingBox(texts.get(i))) - - + + return res - - + + def getBoundingBox(self, textNode): """ Create a bounding box the size of the given text node. Note that this temporarily modifies the document to surround this node with a Span. - + @param textNode Text to create bounding box around @return a bounding box """ @@ -121,47 +121,47 @@ def getBoundingBox(self, textNode): HtmlBBox res = HtmlBBox(el) unSurround(el) return res - - + + def getBoundingBox(self, textNode, offset): """ Create a bounding box around the single character at the offset given within a text node. If the offset is at the end of the text, the bounding box is a point. Temporarily modifies the document as indicated in getBoundingBox(textNode, offset1, offset2) - + @param textNode Text node to find character in @param offset offset of the character @return a bounding box """ return getBoundingBox(textNode, offset, offset if offset == textNode.getLength() else offset+1) - - + + def getBoundingBox(self, textNode, offset1, offset2): """ Create a bounding box the size of the text between the two offsets of the given textNode. Note that this temporarily modifies the document to excise the sub-text into its own span element, which is then used to generate the bounding box. - + @param textNode Text to create bounding box around @param offset1 Starting offset to get bounding box from @param offset2 Ending offset to get bounding box from - + @return a bounding box """ HtmlBBox res - + String text = textNode.getData() int len = text.length() if (offset1 == 0) and (offset2 == len): # Shortcut return getBoundingBox(textNode) - + if (offset2 > len) or (offset1 > offset2): return None - - + + # If this is a cursor, we still need to outline one character boolean isCursor = (offset1 == offset2) boolean posRight = False @@ -169,12 +169,12 @@ def getBoundingBox(self, textNode, offset1, offset2): if offset1 == len: offset1-- posRight = True - + else: offset2++ - - - + + + # Create 2 or 3 spans of this text, so we can measure List<Element> nodes = ArrayList<Element>(3) Element tmpSpan, measureSpan @@ -183,28 +183,28 @@ def getBoundingBox(self, textNode, offset1, offset2): tmpSpan = DOM.createSpan() tmpSpan.setInnerHTML(text.substring(0, offset1)) nodes.add(tmpSpan) - - + + # Middle, the one we measure measureSpan = DOM.createSpan() measureSpan.setInnerHTML(text.substring(offset1, offset2)) nodes.add(measureSpan) - + if offset2 < (len - 1): # Last tmpSpan = DOM.createSpan() tmpSpan.setInnerHTML(text.substring(offset2 + 1)) nodes.add(tmpSpan) - - + + Node parent = textNode.getParentNode() - + for Node node : nodes: parent.insertBefore(node, textNode) - - + + parent.removeChild(textNode) - + if isCursor: # Just make a 0-width version, depending on left or right res = HtmlBBox(measureSpan.getAbsoluteLeft() + @@ -212,40 +212,40 @@ def getBoundingBox(self, textNode, offset1, offset2): measureSpan.getAbsoluteTop(), 0, measureSpan.getOffsetHeight()) - + else: res = HtmlBBox(measureSpan) - - + + parent.insertBefore(textNode, nodes.get(0)) - + for Node node : nodes: parent.removeChild(node) - - + + return res - - + + def getBoundingBox(self, endPoint): """ Create a bounding box around the single character at the rangeEndPoint given. If the offset is at the end of the text, the bounding box is a point. Temporarily modifies the document as indicated in getBoundingBox(textNode, offset1, offset2) - + @param endPoint End point to find character in @return a bounding box """ return getBoundingBox(endPoint.getTextNode(), endPoint.getOffset()) - - + + def getBoundingBox(self, endPoint, asStart): """ Create a bounding box around the text of the rangeEndPoint specified, either to the end or the beginning of the endPoint's text node. Temporarily modifies the document as indicated in getBoundingBox(textNode, offset1, offset2) - + @param endPoint End point to find character in @param asStart Whether to get text from here to end (True) or from start to here (False) @@ -254,24 +254,24 @@ def getBoundingBox(self, endPoint, asStart): return getBoundingBox(endPoint.getTextNode(), endPoint.getOffset() if asStart else 0, endPoint.getTextNode().getLength() if asStart else endPoint.getOffset()) - - + + def getBoundingBox(self, wid): """ Create a bounding box around a widget. - + @param wid Widget to get bounding box of @return a bounding box """ return getBoundingBox(wid.getElement()) - - + + # Some random DOM utility functions - + def getChildIndex(self, child): """ Determine the index of a node within its parent - + @param child A node to determine the index of @return index of the node, or -1 on failure """ @@ -282,17 +282,17 @@ def getChildIndex(self, child): if child == parent.getChild(i): res = i break - - - + + + return res - - + + def unSurround(self, parent): """ Move all children of this element up into its place, and remove the element. - + @param parent element to replace with its children """ Node superParent = parent.getParentNode() @@ -300,22 +300,22 @@ def unSurround(self, parent): while (child = parent.getFirstChild()) is not None: parent.removeChild(child) superParent.insertBefore(child, parent) - + superParent.removeChild(parent) - - + + def surround(self, toChild, newParent): """ Move a node inside of a parent element, maintaining it within the DOM - + @param toChild Node to make into a child @param newParent Element to make into a parent in its place """ toChild.getParentElement().insertBefore(newParent, toChild) newParent.appendChild(toChild) - - - + + + int getAbsoluteLeft() {return self.m_x;} int getAbsoluteTop() {return self.m_y;} int getAbsoluteRight() {return self.m_x + self.m_width;} @@ -324,20 +324,20 @@ def surround(self, toChild, newParent): int getOffsetHeight() {return self.m_height;} int getCenterX() {return self.m_x + self.m_width / 2;} int getCenterY() {return self.m_y + self.m_height / 2;} - + @Override def equals(self, o): try: HtmlBBox comp = (HtmlBBox)o - - return (comp.getAbsoluteLeft() == self.m_x) and - (comp.getAbsoluteTop() == self.m_y) and - (comp.getOffsetHeight() == self.m_height) and + + return (comp.getAbsoluteLeft() == self.m_x) and + (comp.getAbsoluteTop() == self.m_y) and + (comp.getOffsetHeight() == self.m_height) and (comp.getOffsetWidth() == self.m_width) - + catch (Exception ex) {} - + return False - + diff --git a/library/pyjamas/selection/Range.py b/library/pyjamas/selection/Range.py index 6ab282ad2..7b5098c08 100644 --- a/library/pyjamas/selection/Range.py +++ b/library/pyjamas/selection/Range.py @@ -47,7 +47,7 @@ def getIntProp(obj, propertyName): """ Reads an object's property as an integer value. - + @param object The object @param propertyName The name of the property being read @return The value @@ -58,7 +58,7 @@ def getIntProp(obj, propertyName): def getProperty(obj, propertyName): """ Reads an object given a property and returns it as a JavaScriptObject - + @param object @param propertyName @return the object @@ -70,7 +70,7 @@ def cloneRange(rng): """ Make a copy of the given js range; the JS range is decoupled from any changes. - + @param range a js range to copy @return a full copy of the range """ @@ -80,7 +80,7 @@ def cloneRange(rng): def collapse(rng, start): """ Collapse a JS range object to the start or end point - + @param range js range to collapse @param start if True, collapse to start, otherwise to end """ @@ -91,7 +91,7 @@ def compareBoundaryPoint(rng, compare, how): """ Compare endpoints of 2 ranges, returning -1, 0, or 1 depending on whether the compare endpoint comes before, at, or after the range endpoint. - + @param range range to compare against @param compare range to compare @param how a constant to choose which endpoint of each range to compare, @@ -105,7 +105,7 @@ def copyContents(rng, copyInto): """ Copy the contents of the range into the given element, including any tags needed to make it complete. The DOM is not changed. - + @param range js range to copy contents out of. @param copyInto an element to copy these contents into """ @@ -115,7 +115,7 @@ def copyContents(rng, copyInto): def createFromDocument(doc): """ Create an empty JS range from a document - + @param doc DOM document @return a empty JS range """ @@ -125,7 +125,7 @@ def createFromDocument(doc): def createRange(doc, startPoint, startOffset, endPoint, endOffset): """ Create a JS range with the given endpoints - + @param startPoint Start text of the selection @param startOffset offset into start text @param endPoint End text of the selection @@ -142,7 +142,7 @@ def createRange(doc, startPoint, startOffset, endPoint, endOffset): def deleteContents(rng): """ Remove the contents of the js range from the DOM - + @param range js range to remove """ rng.deleteContents() @@ -153,7 +153,7 @@ def extractContents(rng, copyInto): Extract the contents of the range into the given element, removing them from the DOM. Any tags needed to make the contents complete are included. Element object ids are not maintained. - + @param range js range to extract contents from @param copyInto an element to extract these contents into """ @@ -164,7 +164,7 @@ def fillRangePoints(fillRange): """ Fill the start and end point of a Range object, using the javascript range. - + @param fillRange range object to set the endpoints of """ jsRange = fillRange._getJSRange() @@ -187,7 +187,7 @@ def fillRangePoints(fillRange): def getCommonAncestor(rng): """ Get lowest common ancestor element of the given js range - + @param range js range to get ancestor element of @return the lowest element that completely encompasses the range """ @@ -198,7 +198,7 @@ def getHtmlText(rng): """ Get the complete html fragment enclosed by this range. Ensures that all opening and closing tags are included. - + @param range js range to get the html of @return an html string of the range """ @@ -209,7 +209,7 @@ def getHtmlText(rng): def getText(rng): """ Get the pure text that is included in a js range - + @param range js range to get the text of @return string of the range's text """ @@ -221,7 +221,7 @@ def surroundContents(rng, copyInto): Surround the contents of the range with the given element, and put the element in their place. Any tags needed to make the contents complete are included. Element object ids are not maintained. - + @param range js range to surround with this element @param copyInto element to surround the range's contents with """ @@ -234,7 +234,7 @@ def findTextPoint(node, offset): If the found range is not on a text node, this finds the cooresponding text node to where the selection is. If it is on a text node, just directly creates the endpoint from it. - + @param node node returned as an endpoint of a range @param offset offset returned to the endpoint of a range @return A range end point with a proper (or None) text node @@ -272,7 +272,7 @@ def getSelectedTextElements(self, startNode=None, endNode=None): """ Returns all text nodes between (and including) two arbitrary text nodes. Caller must ensure startNode comes before endNode. - + @param startNode start node to traverse @param endNode end node to finish traversal @return A list of all text nodes between these two text nodes @@ -304,25 +304,25 @@ def getSelectedTextElements(self, startNode=None, endNode=None): def __init__(self, arg1, arg2=None): """ Creates an empty range on this document - + @param doc Document to create an empty range in Creates a range that encompasses the given element - + @param element Element to create a range around Creates a range that is a cursor at the given location - + @param cursorPoint a single point to make a cursor range Create a range that extends between the given points. Caller must ensure that end comes after start - + @param startPoint start point of the range @param endPoint end point of the range Internal method for creating a range from a JS object - + @param document @param rangeObj """ @@ -350,7 +350,7 @@ def _getJSRange(self): """ Internal function for retrieving the range, external callers should NOT USE THIS - + @return """ return self.m_range @@ -360,7 +360,7 @@ def _setRange(self, startPoint, endPoint): """ Internal call to set the range, which skips some checks and settings this SHOULD NOT be used externally. - + @param startPoint @param endPoint """ @@ -372,7 +372,7 @@ def _setRange(self, startPoint, endPoint): def collapse(self, start): """ Collapses the range into a cursor, either to the start or end point - + @param start if True, cursor is the start point, otherwise the end point """ if self.m_range is not None: @@ -392,7 +392,7 @@ def compareBoundaryPoint(self, compare, how): returning -1, 0, or 1 depending whether the comparison endpoint comes before, at, or after this endpoint. how is a constant determining which endpoints to compare, for example Range.START_TO_START. - + @param compare Range to compare against this one. @param how constant indicating which endpoints to compare @return -1, 0, or 1 indicating relative order of the endpoints @@ -407,7 +407,7 @@ def copyContents(self, copyInto): """ Make a copy of the contents of this range, into the given element. All tags required to make the range complete will be included - + @param copyInto an element to copy the contents into, ie DOM.createSpanElement() """ @@ -445,7 +445,7 @@ def extractContents(self): Place the contents of this range into a SPAN element, removing them from the DOM. All tags required to make the range complete will be included. This does not preserve the element object ids of the contents. - + @return a SPAN element unattached to the DOM, containing the range contents. """ @@ -459,7 +459,7 @@ def extractContents(self, copyInto): Place the contents of this range into the given element, removing them from the DOM. All tags required to make the range complete will be included. This does not preserve the element object ids of the contents. - + @param copyInto an element to extract the contents into, ie DOM.createSpanElement() """ @@ -471,7 +471,7 @@ def getCommonAncestor(self): """* Get the element that is the lowest common ancestor of both ends of the range. In other words, the smallest element that includes the range. - + @return the element that completely encompasses this range """ self.ensureRange() @@ -482,7 +482,7 @@ def getCursor(self): """ Gets a single point of the cursor location if this is a cursor, otherwise returns None. - + @return the single point if this is a cursor and not a selection """ return self.isCursor() and self.m_startPoint or None @@ -491,7 +491,7 @@ def getCursor(self): def getDocument(self): """ Get the DOM Document this range is within - + @return document this range is in """ return self.m_document @@ -501,7 +501,7 @@ def getEndPoint(self): """ Get the end point of the range. Not a copy, so changing this alters the range. - + @return the end point object """ self.ensureEndPoints() @@ -511,7 +511,7 @@ def getEndPoint(self): def getHtmlText(self): """ Gets an HTML string represnting all elements enclosed by this range. - + @return An html string of this range """ self.ensureRange() @@ -522,7 +522,7 @@ def getJSRange(self): """ Get the JS object representing this range. Since it is highly browser dependent, it is not recommended to operate on this - + @return JavaScriptObject representing this range """ self.ensureRange() @@ -533,7 +533,7 @@ def getStartPoint(self): """ Get the start point of the range. Not a copy, so changing this alters the range. - + @return the start point object """ self.ensureEndPoints() @@ -543,7 +543,7 @@ def getStartPoint(self): def getText(self): """ Gets the plain text that is enclosed by this range - + @return A string of the text in this range """ self.ensureRange() @@ -553,7 +553,7 @@ def getText(self): def isCursor(self): """ Returns whether this is a cursor, ie the start and end point are equal - + @return True if start == end """ self.ensureEndPoints() @@ -576,7 +576,7 @@ def moveToBoundary(self, topMostNode, type): """ TODO NOT IMPLEMENTED YET Move the end points to encompass a boundary type, such as a word. - + @param topMostNode a Node not to traverse above, or None @param type unit to move boundary by, such as RangeEndPoint.MOVE_WORD """ @@ -588,7 +588,7 @@ def moveToBoundary(self, topMostNode, type): def setCursor(self, cursorPoint): """ Sets the range to a point cursor. - + @param cursorPoint A single endpoint to create a cursor range at """ self.setRange(cursorPoint, cursorPoint) @@ -598,7 +598,7 @@ def setEndPoint(self, endPoint): """ Sets just the end point of the range. New endPoint must reside within the same document as the current startpoint, and must occur after it. - + @param startPoint New start point for this range """ assert ((self.m_startPoint is not None) or @@ -611,13 +611,13 @@ def setRange(self, arg1, arg2=None): """ Sets the range to encompass the given element. May not work around non-text containing elements. - + @param element Element to surround by this range @return whether a range can be placed around this element. Set the range to be between the two given points. Both points must be within the same document, and end must come after start. - + @param startPoint Start point to set the range to @param endPoint End point to set the range to """ @@ -645,7 +645,7 @@ def setStartPoint(self, startPoint): """ Sets just the start point of the range. New startPoint must reside within the same document as the current endpoint, and must occur before it. - + @param startPoint New start point for this range """ assert ((self.m_endPoint is not None) and @@ -662,11 +662,11 @@ def surroundContents(self, copyInto=None): complete are included in the child content. This does not preserve the element object ids of the contents. The range will surround this element after this operation. - + @param copyInto an element to place the contents into, which will replace them in the DOM after this operation """ - + if copyInto is None: copyInto = self.m_document.createElement("span") self.ensureRange() @@ -716,7 +716,7 @@ def setupLastEndpoints(self): def setDocument(self, doc): """ Set the document this range is contained within - + @param doc document to set """ if self.m_document != doc: diff --git a/library/pyjamas/selection/RangeEndPoint.py b/library/pyjamas/selection/RangeEndPoint.py index 1f9962149..281fbdc0c 100644 --- a/library/pyjamas/selection/RangeEndPoint.py +++ b/library/pyjamas/selection/RangeEndPoint.py @@ -72,7 +72,7 @@ def __init__(self, arg1, arg2=None): """ Create a range end point at the start or end of an element. The actual selection will occur at the first/last text node within this element. - + @param element: element to create this end point in @param start: whether to make the end point at the start or the end """ @@ -110,7 +110,7 @@ def equals(self, obj): def getOffset(self): """ Get the offset into the text node - + @return offset in characters """ return self.m_offset @@ -119,11 +119,11 @@ def getString(self, asStart): """ Get the string of the text node of this end point, either up to or starting from the offset: - + "som|e text" True : "e text" False : "som" - + @param asStart whether to get the text as if this is a start point @return the text before or after the offset, or None if this is not set """ @@ -145,7 +145,7 @@ def getTextNode(self): """ Get the text node of this end point, note this can be None if there are no text anchors available or if this is just an element. - + @return the text node """ if isTextNode(self.m_node): @@ -155,7 +155,7 @@ def getTextNode(self): def getElement(self): """ Get the Element of this end point, if this is not a textual end point. - + @return the text node """ if self.isTextNode(): @@ -172,7 +172,7 @@ def minimizeBoundaryTextNodes(self, asStart): text nodes where 0 characters are actually used. If asStart is True then move a cursor at the end of a text node to the beginning of the next vice versa for False. - + @param asStart Whether to do this as a start or end range point """ text = self.getTextNode() @@ -190,7 +190,7 @@ def move(self, forward, topMostNode, limit, type, count): TODO IMPLEMENTED ONLY FOR CHARACTER Move the end point forwards or backwards by one unit of type, such as by a word. - + @param forward True if moving forward @param topMostNode top node to not move past, or None @param limit an endpoint not to move past, or None @@ -281,7 +281,7 @@ def findLocation(self, element, absX, absY): non-textual element, a non-text endpoint is returned. If the point falls within a text-containing element but not within any of the actual child text, tries to find the closest text point. - + @param element An element this point falls within @param absX Absolute X coordinate, ie from Event.getClientX @param absY Absolute Y coordinate, ie from Event.getClientY @@ -526,7 +526,7 @@ def isVisible(self, doc, ele): def setOffset(self, offset): """ Set the offset into the text node - + @param offset offset in characters """ self.m_offset = offset @@ -535,7 +535,7 @@ def setOffset(self, offset): def setTextNode(self, textNode, start=None): """ Set this range end point at the start or end of a text node - + @param text text node this end point starts/end in @param start whether to make the end point at the start or the end """ @@ -550,7 +550,7 @@ def setElement(self, element, start=None): """ Set the range end point at the start or end of an element. The actual selection will occur at the first/last text node within this element. - + @param element element to set this end point in @param start whether to make the end point at the start or the end """ @@ -563,7 +563,7 @@ def setElement(self, element, start=None): def __str__(self): """ Get the text of this with a "|" at the offset - + @return a string representation of this endpoint """ return self.getString(False) + "|" + self.getString(True) diff --git a/library/pyjamas/selection/SelectionImpl.ie6.py b/library/pyjamas/selection/SelectionImpl.ie6.py index f6634f49a..f45aef908 100644 --- a/library/pyjamas/selection/SelectionImpl.ie6.py +++ b/library/pyjamas/selection/SelectionImpl.ie6.py @@ -38,7 +38,7 @@ def getJSRange(doc, selection): * @see SelectionImpl#getJSRange """ res = selection.createRange() - + parent = res.parentElement() if parent.ownerDocument == doc: return res.duplicate() diff --git a/library/pyjamas/selection/SelectionImpl.py b/library/pyjamas/selection/SelectionImpl.py index 4edd3e9c9..6b988db33 100644 --- a/library/pyjamas/selection/SelectionImpl.py +++ b/library/pyjamas/selection/SelectionImpl.py @@ -27,7 +27,7 @@ * * @author John Kozura """ - + """* * Reads an object's property as a boolean value. * diff --git a/library/pyjamas/ui/Anchor.py b/library/pyjamas/ui/Anchor.py index dea9a5106..60948c056 100644 --- a/library/pyjamas/ui/Anchor.py +++ b/library/pyjamas/ui/Anchor.py @@ -23,25 +23,25 @@ class _Attribute(object): "Attribute definition class with method set and remove" - def __init__(self, element, attribute, + def __init__(self, element, attribute, attribute_type=None, type_restriction=None): self.element = element self.attribute = attribute self._type = attribute_type self._restriction = type_restriction - + def get(self): "Get the value" return DOM.getAttribute(self.element, self.attribute) - + def set(self, value): "Set the value" DOM.setAttribute(self.element, self.attribute, value) - + def remove(self): - "Remove the attribute from the element" + "Remove the attribute from the element" DOM.removeAttribute(self.element, self.attribute) - + class _Attributes(object): "Attribute container class" def __init__(self, element): @@ -53,7 +53,7 @@ def __init__(self, element): self.rev = _Attribute(element, 'rev', 'link-types', 'ci') self.charset = _Attribute(element, 'charset', 'charset', 'ci') self.target = _Attribute(element, 'target', 'target', 'ci') - + class Anchor(Widget, ClickHandler, _Attributes): """Anchor attribute, use this to create the equivalent of the <a></a> tag. The attributes: name, href. hreflang, type, rel, rev, charset are in the @@ -71,7 +71,7 @@ def __init__(self, **kwargs): self.widget = None Widget.__init__(self, **kwargs) ClickHandler.__init__(self) - + def setWidget(self, widget): """ Add child widget """ diff --git a/library/pyjamas/ui/AreaSlider.py b/library/pyjamas/ui/AreaSlider.py index 71a41606a..2ca99bdd2 100644 --- a/library/pyjamas/ui/AreaSlider.py +++ b/library/pyjamas/ui/AreaSlider.py @@ -1,11 +1,11 @@ """ Control Widgets. Presently comprises a Vertical Slider and derivatives. - HorizontalSlider and HorizontalSlider2 added by Bill Winder - AreaSlider and AreaSlider2 added by Bill Winder + HorizontalSlider and HorizontalSlider2 added by Bill Winder + AreaSlider and AreaSlider2 added by Bill Winder Copyright (C) 2008, 2009, 2010 Luke Kenneth Casson Leighton <lkcl@lkcl.net> Copyright (C) 2010 - Cedric Gestes <gestes@aldebaran-robotics.com> - Copyright (C) 2009, 2010 - Bill Winder <wgwinder@gmail.com> + Copyright (C) 2009, 2010 - Bill Winder <wgwinder@gmail.com> To do: All controls with draggable=True do not fire the OnFocus methon on single click. @@ -152,7 +152,7 @@ def setControlPos(self, value): # move the handle DOM.setStyleAttribute(self.handle, "top", "%dpx" % relative_y) - DOM.setStyleAttribute(self.handle, "left", "%dpx" % relative_x) + DOM.setStyleAttribute(self.handle, "left", "%dpx" % relative_x) DOM.setStyleAttribute(self.handle, "position", "absolute") Factory.registerClass('pyjamas.ui.AreaSlider', 'AreaSlider', AreaSlider) diff --git a/library/pyjamas/ui/AutoComplete.py b/library/pyjamas/ui/AutoComplete.py index 52f5175c9..6d0af2b55 100644 --- a/library/pyjamas/ui/AutoComplete.py +++ b/library/pyjamas/ui/AutoComplete.py @@ -29,7 +29,7 @@ def __init__(self, **kwargs): self.choicesPopup.add(self.choices) self.choicesPopup.addStyleName("AutoCompleteChoices") - + self.choices.setStyleName("list") if not kwargs.has_key('StyleName'): kwargs['StyleName']="gwt-AutoCompleteTextBox" @@ -40,7 +40,7 @@ def __init__(self, **kwargs): def setCompletionItems(self, items): if not hasattr(items, 'getCompletionItems'): items = SimpleAutoCompletionItems(items) - + self.items = items def getCompletionItems(self): @@ -58,7 +58,7 @@ def onKeyUp(self, arg0, arg1, arg2): selectedIndex += 1 if selectedIndex >= self.choices.getItemCount(): selectedIndex = 0 - self.choices.setSelectedIndex(selectedIndex) + self.choices.setSelectedIndex(selectedIndex) return if arg1 == KeyboardListener.KEY_UP: @@ -71,7 +71,7 @@ def onKeyUp(self, arg0, arg1, arg2): if arg1 == KeyboardListener.KEY_ENTER: if self.visible: - self.complete() + self.complete() return if arg1 == KeyboardListener.KEY_ESCAPE: @@ -90,13 +90,13 @@ def onKeyUp(self, arg0, arg1, arg2): for i in range(len(matches)): self.choices.addItem(matches[i]) - + if len(matches) == 1 and matches[0] == text: self.choicesPopup.hide() else: self.choices.setSelectedIndex(0) self.choices.setVisibleItemCount(len(matches) + 1) - + if not self.popupAdded: RootPanel().add(self.choicesPopup) self.popupAdded = True @@ -118,7 +118,7 @@ def onClick(self, arg0): def complete(self): if self.choices.getItemCount() > 0: self.setText(self.choices.getItemText(self.choices.getSelectedIndex())) - + self.choices.clear() self.choicesPopup.hide() self.setFocus(True) @@ -136,10 +136,10 @@ def __init__(self, items = None): def getCompletionItems(self, match): matches = [] match = match.lower() - + for i in range(len(self.completions)): lower = self.completions[i].lower() if lower.startswith(match): matches.append(self.completions[i]) - + return matches diff --git a/library/pyjamas/ui/BuilderWidget.py b/library/pyjamas/ui/BuilderWidget.py index bef2dba5d..670e1c192 100644 --- a/library/pyjamas/ui/BuilderWidget.py +++ b/library/pyjamas/ui/BuilderWidget.py @@ -58,7 +58,7 @@ def onSomeRandomClickThing(self, sender): class BuilderWidget(Composite): def __init__(self, **kwargs): - + self.b = None self.text = None self.instance_name = None diff --git a/library/pyjamas/ui/CSS.py b/library/pyjamas/ui/CSS.py index de77b2d2f..71ee56d82 100644 --- a/library/pyjamas/ui/CSS.py +++ b/library/pyjamas/ui/CSS.py @@ -18,15 +18,15 @@ def __init__(self, cssFile='', _doc=None): print "css file", cssFile if _doc is None: _doc = doc() - _doc.getElementsByTagName("head").item(0).appendChild(self._e) + _doc.getElementsByTagName("head").item(0).appendChild(self._e) def remove(self): parent = DOM.getParent(self._e) - DOM.removeChild(parent, self._e) - + DOM.removeChild(parent, self._e) + def setStyleElementText(el, text): DOM.appendChild(el, doc().createTextNode(text)) - + class StyleSheetCssText: def __init__(self, text='', _doc=None): @@ -36,9 +36,9 @@ def __init__(self, text='', _doc=None): if _doc is None: _doc = doc() - _doc.getElementsByTagName("head").item(0).appendChild(self._e) + _doc.getElementsByTagName("head").item(0).appendChild(self._e) def remove(self): parent = DOM.getParent(self._e) - DOM.removeChild(parent, self._e) - + DOM.removeChild(parent, self._e) + diff --git a/library/pyjamas/ui/Calendar.py b/library/pyjamas/ui/Calendar.py index 9a3d452fe..0a4c54fd9 100644 --- a/library/pyjamas/ui/Calendar.py +++ b/library/pyjamas/ui/Calendar.py @@ -24,7 +24,7 @@ from datetime import datetime class Calendar(FocusPanel): - monthsOfYear = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + monthsOfYear = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] daysOfWeek = ['S', 'M', 'T', 'W', 'T', 'F', 'S'] today = 'Today' @@ -101,7 +101,7 @@ def show(self, left, top): self.setVisible(True) def drawCurrent(self): - yr, mth, day = self.currentYear, self.currentMonth, self.currentDay + yr, mth, day = self.currentYear, self.currentMonth, self.currentDay self.draw(int(mth), int(yr)) @@ -300,7 +300,7 @@ def onCellClicked(self, grid, row, col): # well if anyone is listening to the listener, fire that event for listener in self.selectedDateListeners: if hasattr(listener, "onDateSelected"): - listener.onDateSelected(self.currentYear, self.currentMonth, + listener.onDateSelected(self.currentYear, self.currentMonth, selectedDay) else: listener(self.currentYear, self.currentMonth, selectedDay) diff --git a/library/pyjamas/ui/CheckBox.py b/library/pyjamas/ui/CheckBox.py index 1f15770ae..955b7f60e 100644 --- a/library/pyjamas/ui/CheckBox.py +++ b/library/pyjamas/ui/CheckBox.py @@ -39,7 +39,7 @@ def __init__(self, label=None, asHTML=False, **ka): def _getProps(self): return ButtonBase._getProps() + self._props - + def sinkEvents(self, eventBitsToAdd): """ Unlike other widgets the CheckBox sinks on its inputElement, not its wrapper @@ -85,7 +85,7 @@ def isChecked(self): """ XXX this function is deprecated: use getChecked """ return self.getChecked() - + def getChecked(self): if self.isAttached(): propName = "checked" diff --git a/library/pyjamas/ui/ClickListener.py b/library/pyjamas/ui/ClickListener.py index 8cae7b30a..cbd199c09 100644 --- a/library/pyjamas/ui/ClickListener.py +++ b/library/pyjamas/ui/ClickListener.py @@ -1,6 +1,6 @@ -""" +""" Copyright (C) 2008, 2009 - Luke Kenneth Casson Leighton <lkcl@lkcl.net> - + """ from pyjamas import DOM from pyjamas.ui import Event @@ -11,7 +11,7 @@ def __init__(self, preventDefault=False): self._clickListeners = [] self._doubleclickListeners = [] self._clickPreventDefault = preventDefault - + self.sinkEvents(Event.ONCLICK) self.sinkEvents(Event.ONDBLCLICK) @@ -28,8 +28,8 @@ def addClickListener(self, listener): self._clickListeners.append(listener) def onBrowserEvent(self, event): - """Listen to events raised by the browser and call the appropriate - method of the listener (widget, ..) object. + """Listen to events raised by the browser and call the appropriate + method of the listener (widget, ..) object. """ type = DOM.eventGetType(event) if type == "click": diff --git a/library/pyjamas/ui/Controls.py b/library/pyjamas/ui/Controls.py index 7ca01156c..46abee8fc 100644 --- a/library/pyjamas/ui/Controls.py +++ b/library/pyjamas/ui/Controls.py @@ -1,14 +1,14 @@ """ Control Widgets. Presently comprises a Vertical Slider Demo and derivatives. - HorizontalDemoSlider and HorizontalDemoSlider2 added by Bill Winder - AreaDemoSlider and AreaDemoSlider2 added by Bill Winder + HorizontalDemoSlider and HorizontalDemoSlider2 added by Bill Winder + AreaDemoSlider and AreaDemoSlider2 added by Bill Winder Copyright (C) 2008, 2009, 2010 Luke Kenneth Casson Leighton <lkcl@lkcl.net> Copyright (C) 2010 - Cedric Gestes <gestes@aldebaran-robotics.com> - Copyright (C) 2009, 2010 - Bill Winder <wgwinder@gmail.com> + Copyright (C) 2009, 2010 - Bill Winder <wgwinder@gmail.com> - To do: All controls with draggable=True do not fire the OnFocus methon on single click. + To do: All controls with draggable=True do not fire the OnFocus methon on single click. the control does not activate the OnFocus method. Clicking the handle does fire OnFocus, however. """ diff --git a/library/pyjamas/ui/DecoratorPanel.py b/library/pyjamas/ui/DecoratorPanel.py index 119978fcf..4d4154577 100644 --- a/library/pyjamas/ui/DecoratorPanel.py +++ b/library/pyjamas/ui/DecoratorPanel.py @@ -8,10 +8,10 @@ from pyjamas.ui.TabBar import TabBar """ - + A {@link SimplePanel} that wraps its contents in stylized boxes, which can be used to add rounded corners to a {@link Widget}. - + Wrapping a {@link Widget} in a "9-box" allows users to specify images in each of the corners and along the four borders. This method allows the content within the {@link DecoratorPanel} to resize without disrupting the look of @@ -20,8 +20,8 @@ This class also simplifies the process of using AlphaImageLoaders to support 8-bit transparencies (anti-aliasing and shadows) in ie6, which does not support them normally. - - + + CSS Style Rules .gwt-DecoratorPanel { the panel } @@ -60,11 +60,11 @@ def __init__(self, rowStyles=None, containerIndex=1, **kwargs): apply to each row. Each row will contain three cells (Left, Center, and Right). The Center cell in the containerIndex row will contain the {@link Widget}. - + @param rowStyles: an array of style names to apply to each row @param containerIndex the index of the container row """ - + if rowStyles is None: rowStyles = self.DEFAULT_ROW_STYLENAMES @@ -88,7 +88,7 @@ def __init__(self, rowStyles=None, containerIndex=1, **kwargs): SimplePanel.__init__(self, self.table, **kwargs) # Add each row - for i in range(len(rowStyles)): + for i in range(len(rowStyles)): row = self.createTR(rowStyles[i]) DOM.appendChild(self.tbody, row) if i == containerIndex: @@ -98,10 +98,10 @@ def createTR(self, styleName) : """ Create a new row with a specific style name. The row will contain three cells (Left, Center, and Right), each prefixed with the specified style name. - + This method allows Widgets to reuse the code on a DOM level, without creating a DecoratorPanel Widget. - + @param styleName: the style name @return the new row {@link Element} """ @@ -114,7 +114,7 @@ def createTR(self, styleName) : def createTD(self, styleName): """ Create a new table cell with a specific style name. - + @param styleName: the style name @return the new cell {@link Element} """ @@ -127,7 +127,7 @@ def createTD(self, styleName): def getCellElement(self, row, cell): """ Get a specific Element from the panel. - + @param row: the row index @param cell: the cell index @return the Element at the given row and cell diff --git a/library/pyjamas/ui/DisclosurePanel.py b/library/pyjamas/ui/DisclosurePanel.py index 9552b11a2..79c899556 100644 --- a/library/pyjamas/ui/DisclosurePanel.py +++ b/library/pyjamas/ui/DisclosurePanel.py @@ -17,7 +17,7 @@ from pyjamas import Factory from pyjamas.ui.Widget import Widget from pyjamas.ui.SimplePanel import SimplePanel -from pyjamas.ui.VerticalPanel import VerticalPanel +from pyjamas.ui.VerticalPanel import VerticalPanel from pyjamas.ui import Event from pyjamas import DOM import pygwt @@ -85,7 +85,7 @@ def updateState(self, setOpen): else: DOM.setAttribute(self.imgElem, "src", self.imageBase + "disclosurePanelClosed.png") - + # TODO: must be able to pass in DisclosurePanel argument by a means # *other* than an actual class instance. @@ -120,7 +120,7 @@ def __init__(self, *args, **kwargs): headerWidget = kwargs.pop('header', headerWidget) # TODO: add ImageBundle # images = kwargs.pop('images', None) - + # If both headerText and headerWidget are arguments, headerText will # be used to preserve API compatibility. headerContent = headerWidget diff --git a/library/pyjamas/ui/FlashPanel.browser.py b/library/pyjamas/ui/FlashPanel.browser.py index 2c59faff2..0d033b7d5 100644 --- a/library/pyjamas/ui/FlashPanel.browser.py +++ b/library/pyjamas/ui/FlashPanel.browser.py @@ -8,19 +8,19 @@ """ class FlashPanel(Panel): - + def callFlash(self, functionName, arguments=[]): """ @param functionName: Methodname of ExternalInterface @param arguments: List with arguments of ExternalInterfaces method - + @return: return value of ExternalInterfaces method """ movieElement = self.getMovieElement() if not movieElement: return None try: - returnString = movieElement.CallFunction('<invoke name="%s" returntype="javascript">%s</invoke>' % (functionName, + returnString = movieElement.CallFunction('<invoke name="%s" returntype="javascript">%s</invoke>' % (functionName, self.flashArgumentsToXML(arguments, 0))) returnValue = '' if returnString: @@ -29,13 +29,13 @@ def callFlash(self, functionName, arguments=[]): except: log.debug('Call to '+functionName+' failed') return returnValue - + def toJS(self, list_or_dict): """ @param list_or_dict: A List or a Dictonary - + Converting recrusive Dictonarys and Lists to Javascript Types. - + @return: javascript array or object """ def toArray(self, list): @@ -56,4 +56,4 @@ def toObject(self, dict): elif hasattr(obj, 'append'): obj = toArray(self, obj) return obj - + diff --git a/library/pyjamas/ui/FlashPanel.py b/library/pyjamas/ui/FlashPanel.py index e9e9f0ca0..2b9b9a44b 100644 --- a/library/pyjamas/ui/FlashPanel.py +++ b/library/pyjamas/ui/FlashPanel.py @@ -21,11 +21,11 @@ def browser(): return 'w3c' class FlashPanel(Panel): - + def __init__(self, **kwargs): element = DOM.createDiv() self.setElement(element) - + self.object_id = 'FlashObject' """ id of the object-tag. Default: FlashObject """ self.object_class = None @@ -53,58 +53,58 @@ def __init__(self, **kwargs): #log.debug('FlashPanel loaded on %s' % self.browser) Panel.__init__(self, **kwargs) - + def onLoad(self): DOM.setInnerHTML(self.element, self.__getFlashHTML()) - + def getObjectID(self): """ @return: id of the object-tag """ return self.object_id - + def setObjectID(self, object_id): """ @param object_id: The id of the object-tag """ self.object_id = object_id - + def getObjectClass(self): """ @return: class-name of the object-tag """ return self.object_class - + def setObjectClass(self, object_class): """ @param object_class: The class-name of the object-tag """ self.object_class = object_class - + def getObjectWidth(self): """ @return: width parameter of the object-tag """ return self.object_width - + def setObjectWidth(self, width): """ @param width: The width parameter of the object-tag """ self.object_width = str(width) - + def getObjectHeight(self): """ @return: height parameter of the object-tag """ return self.object_height - + def setObjectHeight(self, height): """ @param height: The height parameter of the object-tag """ self.object_height = str(height) - + def getFlashUrl(self): """ @return: url of the flashmovie @@ -116,31 +116,31 @@ def setFlashUrl(self, flash_url): @param flash_url: The url of the flash_movie """ self.flash_url = flash_url - + def getWmode(self): """ @return: flash parameter wmode """ return self.wmode - + def setWmode(self, wmode): """ @param wmode: The flash parameter wmode """ self.wmode = wmode - + def getQuality(self): """ @return: flash parameter quality """ return self.quality - + def setQuality(self, quality): """ @param quality: The flash parameter quality """ self.quality = quality - + def getMenu(self): """ @return: flash parameter menu @@ -149,7 +149,7 @@ def getMenu(self): return True else: return False - + def setMenu(self, menu): """ @param menu: The flash parameter menu @@ -158,7 +158,7 @@ def setMenu(self, menu): self.menu = 'true' else: self.menu = 'false' - + def getAllowFullscreen(self): """ @return: flash parameter allowfullscreen @@ -167,7 +167,7 @@ def getAllowFullscreen(self): return True else: return False - + def setAllowFullscreen(self, allowFullscreen): """ @param allowFullscreen: The flash parameter allowfullscreen @@ -176,31 +176,31 @@ def setAllowFullscreen(self, allowFullscreen): self.allowFullscreen = 'true' else: self.allowFullscreen = 'false' - + def getBGColor(self): """ @return: flash parameter bgcolor """ return self.bgColor - + def setBGColor(self, bgcolor): """ @param bgcolor: The flash parameter bgcolor """ self.bgColor = bgcolor - + def getFlashVars(self): """ @return: flash parameter flashvars """ return self.flashvars - + def setFlashVars(self, flashvars): """ @param flashvars: The flash parameter flashvars """ self.flashvars = flashvars - + def __getFlashHTML(self): obj = 'id="'+self.object_id+'"' if self.object_width: @@ -212,7 +212,7 @@ def __getFlashHTML(self): if self.browser == 'ie': obj += ' classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' else: - obj += ' type="application/x-shockwave-flash"' + obj += ' type="application/x-shockwave-flash"' obj += ' data="'+self.flash_url+'"' html = ['<object %s>' % obj] if self.flash_url: @@ -239,32 +239,32 @@ def __getFlashHTML(self): </div> """) html.append('</object>') - + flashvars = ''.join(html) return flashvars - + def getMovieElement(self): """ @return: element DOM-Object of the object-tag - """ + """ element = DOM.getElementById(self.object_id) return element - + def callFlash(self, functionName, arguments=[]): """ @param functionName: Methodname of ExternalInterface @param arguments: List with arguments of ExternalInterfaces method - + @return: return value of ExternalInterfaces method """ raise NotImplemented("calling of javascript and conversion of javascript parameters is required") - + def toJS(self, list_or_dict): """ @param list_or_dict: A List or a Dictonary - + Converting recrusive Dictonarys and Lists to Javascript Types. - + @return: javascript array or object """ raise NotImplemented("conversion of javascript parameters is required") @@ -275,5 +275,5 @@ def flashArgumentsToXML(self, arguments, num): """ arguments = self.toJS(arguments) return wnd().__flash__argumentsToXML(arguments, num); - - + + diff --git a/library/pyjamas/ui/FlexTable.py b/library/pyjamas/ui/FlexTable.py index a05d9a266..e9c9d1471 100644 --- a/library/pyjamas/ui/FlexTable.py +++ b/library/pyjamas/ui/FlexTable.py @@ -21,7 +21,7 @@ from pyjamas.ui.HTMLTable import HTMLTable from pyjamas.ui.RowFormatter import RowFormatter -from pyjamas.ui.FlexCellFormatter import FlexCellFormatter +from pyjamas.ui.FlexCellFormatter import FlexCellFormatter class FlexTable(HTMLTable): def __init__(self, **kwargs): diff --git a/library/pyjamas/ui/Focus.mozilla.py b/library/pyjamas/ui/Focus.mozilla.py index 46f4fb1fb..405170f68 100644 --- a/library/pyjamas/ui/Focus.mozilla.py +++ b/library/pyjamas/ui/Focus.mozilla.py @@ -17,7 +17,7 @@ def createFocusHandler(): $wnd.setTimeout(function() { div.focus(); }, 0); - } + } }; """) diff --git a/library/pyjamas/ui/Focus.oldmoz.py b/library/pyjamas/ui/Focus.oldmoz.py index 2e7ba54e9..54a95de43 100644 --- a/library/pyjamas/ui/Focus.oldmoz.py +++ b/library/pyjamas/ui/Focus.oldmoz.py @@ -17,7 +17,7 @@ def createFocusHandler(): $wnd.setTimeout(function() { div.focus(); }, 0); - } + } }; """) diff --git a/library/pyjamas/ui/Focus.opera.py b/library/pyjamas/ui/Focus.opera.py index 46f4fb1fb..405170f68 100644 --- a/library/pyjamas/ui/Focus.opera.py +++ b/library/pyjamas/ui/Focus.opera.py @@ -17,7 +17,7 @@ def createFocusHandler(): $wnd.setTimeout(function() { div.focus(); }, 0); - } + } }; """) diff --git a/library/pyjamas/ui/Focus.py b/library/pyjamas/ui/Focus.py index 7f058b3ac..c5fcbab64 100644 --- a/library/pyjamas/ui/Focus.py +++ b/library/pyjamas/ui/Focus.py @@ -25,11 +25,11 @@ def ensureFocusHandler(): pass def createFocusHandler(): - pass + pass def createFocusable0(): pass - + def blur(elem): elem.blur() @@ -86,7 +86,7 @@ def isReadonly(self): return True except AttributeError: return True - + def setReadonly(self, readonly): DOM.setBooleanAttribute(self.getElement(), "readOnly", readonly) diff --git a/library/pyjamas/ui/Focus.safari.py b/library/pyjamas/ui/Focus.safari.py index 7108ccdb7..8d865119d 100644 --- a/library/pyjamas/ui/Focus.safari.py +++ b/library/pyjamas/ui/Focus.safari.py @@ -18,7 +18,7 @@ def createFocusHandler(): $wnd.setTimeout(function() { div.focus(); }, 0); - } + } }; """) diff --git a/library/pyjamas/ui/FocusPanel.py b/library/pyjamas/ui/FocusPanel.py index 53c10cdc9..b467eb0d5 100644 --- a/library/pyjamas/ui/FocusPanel.py +++ b/library/pyjamas/ui/FocusPanel.py @@ -29,7 +29,7 @@ class FocusPanel(SimplePanel, FocusHandler, KeyboardHandler, FocusMixin): def __init__(self, **kwargs): - """ pass in Widget={the widget} so that Applier will call setWidget. + """ pass in Widget={the widget} so that Applier will call setWidget. """ SimplePanel.__init__(self, Focus.createFocusable(), **kwargs) diff --git a/library/pyjamas/ui/FormPanel.ie6.py b/library/pyjamas/ui/FormPanel.ie6.py index 5905de791..c66d80697 100644 --- a/library/pyjamas/ui/FormPanel.ie6.py +++ b/library/pyjamas/ui/FormPanel.ie6.py @@ -4,7 +4,7 @@ def getTextContents(self, iframe): try { if (!@{{iframe}}.contentWindow.document) return null; - + return @{{iframe}}.contentWindow.document.body.innerText; } catch (e) { return null; @@ -17,7 +17,7 @@ def hookEvents(self, iframe, form, listener): @{{iframe}}.onreadystatechange = function() { if (!@{{iframe}}.__formAction) return; - + if (@{{iframe}}.readyState == 'complete') { @{{listener}}.onFrameLoad(); } diff --git a/library/pyjamas/ui/FormPanel.opera.py b/library/pyjamas/ui/FormPanel.opera.py index f6cf0ceab..5f8b2ecfd 100644 --- a/library/pyjamas/ui/FormPanel.opera.py +++ b/library/pyjamas/ui/FormPanel.opera.py @@ -5,7 +5,7 @@ def getTextContents(self, iframe): try { if (!@{{iframe}}.contentWindow.document) return null; - + return @{{iframe}}.contentWindow.document.body.innerText; } catch (e) { return null; diff --git a/library/pyjamas/ui/HTMLPanel.py b/library/pyjamas/ui/HTMLPanel.py index 714e88de8..356e52dc3 100644 --- a/library/pyjamas/ui/HTMLPanel.py +++ b/library/pyjamas/ui/HTMLPanel.py @@ -35,7 +35,7 @@ def getElementsByTagName(element, tagname): el = _check_tagname(element, tagname) if el: res.append(el) - + it = DOM.walkChildren(element) while True: try: diff --git a/library/pyjamas/ui/HTMLTable.py b/library/pyjamas/ui/HTMLTable.py index ca6bf2bec..d6de076a7 100644 --- a/library/pyjamas/ui/HTMLTable.py +++ b/library/pyjamas/ui/HTMLTable.py @@ -148,7 +148,7 @@ def addIndexedItem(self, index, item): while col >= self.getDOMCellCount(row): self.insertCells(row, self.getDOMCellCount(row), 1) self.setWidget(row, col, item) - + def add(self, item, row, col): self.addIndexedItem((row, col), item) @@ -195,7 +195,7 @@ def _onBrowserEvent(self, event, event_type): def onBrowserEvent(self, event): event_type = DOM.eventGetType(event) if event_type != "dblclick" and event_type != "click": - return + return self._onBrowserEvent(event, event_type) @@ -277,7 +277,7 @@ def _unmapWidget(self, widget): element = widget.getElement() del self.widgetMap[self.computeKeyForElement(element)] del widgethash[element] - + def checkCellBounds(self, row, column): self.checkRowBounds(row) #if column<0: raise IndexError, "Column " + column + " must be non-negative: " + column diff --git a/library/pyjamas/ui/InlineHTML.py b/library/pyjamas/ui/InlineHTML.py index 0648494c4..15b8a0831 100644 --- a/library/pyjamas/ui/InlineHTML.py +++ b/library/pyjamas/ui/InlineHTML.py @@ -18,10 +18,10 @@ class InlineHTML(HTML): '''An HTML, but using <span> instead of <div>''' - + def __init__(self, html=None, wordWrap=True, **kwargs): kwargs['StyleName'] = kwargs.get('StyleName', "gwt-InlineHTML") kwargs['Element'] = DOM.createSpan() HTML.__init__(self, html, wordWrap, **kwargs) - + Factory.registerClass('pyjamas.ui.InlineHTML', 'InlineHTML', InlineHTML) diff --git a/library/pyjamas/ui/InlineLabel.py b/library/pyjamas/ui/InlineLabel.py index eeadce2b3..b86da7b75 100644 --- a/library/pyjamas/ui/InlineLabel.py +++ b/library/pyjamas/ui/InlineLabel.py @@ -18,10 +18,10 @@ class InlineLabel(Label): '''A Label, but using <span> instead of <div>''' - + def __init__(self, text=None, wordWrap=True, **kwargs): kwargs['StyleName'] = kwargs.get('StyleName', "gwt-InlineLabel") kwargs['Element'] = DOM.createSpan() Label.__init__(self, text, wordWrap, **kwargs) - + Factory.registerClass('pyjamas.ui.InlineLabel', 'InlineLabel', InlineLabel) diff --git a/library/pyjamas/ui/Map.py b/library/pyjamas/ui/Map.py index 6542d3b4a..eb1a4ab07 100644 --- a/library/pyjamas/ui/Map.py +++ b/library/pyjamas/ui/Map.py @@ -39,7 +39,7 @@ def add(self, widget): def insert(self, widget, beforeIndex): widget.removeFromParent() ComplexPanel.insert(self, widget, self.getElement(), beforeIndex) - + def setName(self, name): DOM.setAttribute(self.getElement(), "name", name) @@ -63,7 +63,7 @@ def __init__(self, Shape, Coords, **kwargs): ClickHandler.__init__(self, preventDefault=True) def setShape(self, shape): - DOM.setAttribute(self.getElement(), "shape", shape) + DOM.setAttribute(self.getElement(), "shape", shape) def setCoords(self, coords): DOM.setAttribute(self.getElement(), "coords", coords) diff --git a/library/pyjamas/ui/MonthField.py b/library/pyjamas/ui/MonthField.py index d1b673d5a..cbee44ca0 100644 --- a/library/pyjamas/ui/MonthField.py +++ b/library/pyjamas/ui/MonthField.py @@ -7,17 +7,17 @@ from pyjamas.locale import _ class NoDaysCalendar(Calendar): - + cancel = _("Cancel") - monthsOfYear = [_('Jan'), _('Feb'), _('Mar'), _('Apr'), _('May'), _('Jun'), + monthsOfYear = [_('Jan'), _('Feb'), _('Mar'), _('Apr'), _('May'), _('Jun'), _('Jul'), _('Aug'), _('Sep'), _('Oct'), _('Nov'), _('Dec')] - - - + + + def drawGrid(self,month,year): empty = SimplePanel() return empty - + def _gridShortcutsLinks(self): bh1 = Hyperlink(_("Current")) bh1.addClickListener(getattr(self, 'onToday')) @@ -26,27 +26,27 @@ def _gridShortcutsLinks(self): bh3 = Hyperlink(self.cancel) bh3.addClickListener(getattr(self, 'onCancel')) - - + + b = HorizontalPanel() b.addStyleName("calendar-shortcuts") b.add(bh1) b.add(b2) b.add(bh3) - + self.vp.add(b) def _gridCancelLink(self):pass - - + + def onMonthSelected(self,event): self.onDate(event,self.currentYear,self.currentMonth,1) class MonthField(DateField): today_text = _("Current") - + def __init__(self): super(MonthField,self).__init__(format="%Y-%m") self.calendar = NoDaysCalendar() self.calendar.addSelectedDateListener(getattr(self,"onDateSelected")) - + diff --git a/library/pyjamas/ui/MouseListener.py b/library/pyjamas/ui/MouseListener.py index dc2f6e662..27ea1cf0e 100644 --- a/library/pyjamas/ui/MouseListener.py +++ b/library/pyjamas/ui/MouseListener.py @@ -73,7 +73,7 @@ def removeMouseListener(self, listener): def onMouseMove(self, sender, x, y): pass - + def onMouseDown(self, sender, x, y): pass @@ -118,4 +118,4 @@ def removeMouseWheelListener(self, listener): def onMouseWheel(self, sender, velocity): pass - + diff --git a/library/pyjamas/ui/MultiListener.py b/library/pyjamas/ui/MultiListener.py index 59131fc83..e1dd4c986 100644 --- a/library/pyjamas/ui/MultiListener.py +++ b/library/pyjamas/ui/MultiListener.py @@ -2,7 +2,7 @@ class MultiListener(object): # The combinations that are coupled. E.g., if onFocus is defined, then - # onLostFocus should also be defined. The set method will substitute the + # onLostFocus should also be defined. The set method will substitute the # missing methods with the ignore method. # See also pyjamas.builder.Builder.eventListeners combinations = dict( diff --git a/library/pyjamas/ui/PopupPanel.ie6.py b/library/pyjamas/ui/PopupPanel.ie6.py index 2b73a6453..1253c0c67 100644 --- a/library/pyjamas/ui/PopupPanel.ie6.py +++ b/library/pyjamas/ui/PopupPanel.ie6.py @@ -1,5 +1,5 @@ class PopupPanel: - + # PopupImpl.onShow def onShowImpl(self, popup): JS(""" @@ -8,7 +8,7 @@ def onShowImpl(self, popup): frame.frameBorder = 0; frame.style.position = 'absolute'; frame.src = "javascript:''"; - + @{{popup}}.__frame = frame; frame.__popup = @{{popup}}; frame.style.setExpression('left', 'this.__popup.offsetLeft'); diff --git a/library/pyjamas/ui/PopupPanel.mshtml.py b/library/pyjamas/ui/PopupPanel.mshtml.py index 7301259c2..9a6656817 100644 --- a/library/pyjamas/ui/PopupPanel.mshtml.py +++ b/library/pyjamas/ui/PopupPanel.mshtml.py @@ -1,12 +1,12 @@ #class PopupPanel: -# +# # # PopupImpl.onShow # def onShowImpl(self, popup): # frame = doc().createElement('iframe') # frame.scrolling = 'no' # frame.frameBorder = 0 # frame.style.position = 'absolute' -# +# # popup.__frame = frame # frame.__popup = popup # frame.style.setExpression('left', 'this.__popup.offsetLeft') diff --git a/library/pyjamas/ui/PushButton.py b/library/pyjamas/ui/PushButton.py index c186af492..b79bda704 100644 --- a/library/pyjamas/ui/PushButton.py +++ b/library/pyjamas/ui/PushButton.py @@ -23,9 +23,9 @@ class PushButton (CustomButton): CSS: .gwt-PushButton- up/down/up-hovering/down-hovering/up-disabled/down-disabled {.html-face} - """ + """ STYLENAME_DEFAULT = "gwt-PushButton" - + def __init__(self, upImageText = None, downImageText=None, handler = None, **kwargs): """ @@ -35,19 +35,19 @@ def __init__(self, upImageText = None, downImageText=None, handler = None, CustomButton.__init__(self, upImageText, downImageText, handler, **kwargs) - - + + def onClick(self, sender=None): self.setDown(False) CustomButton.onClick(self) - + def onClickCancel(self): self.setDown(False) - + def onClickStart(self): self.setDown(True) - + Factory.registerClass('pyjamas.ui.PushButton', 'PushButton', PushButton) diff --git a/library/pyjamas/ui/RichTextAreaImpl.py b/library/pyjamas/ui/RichTextAreaImpl.py index bfe92121f..fbbefe977 100644 --- a/library/pyjamas/ui/RichTextAreaImpl.py +++ b/library/pyjamas/ui/RichTextAreaImpl.py @@ -30,47 +30,47 @@ * rich text editing. """ class RichTextAreaImpl: - + def __init__(self): self.elem = self.createElement() - - + + def getElement(self): return self.elem - - + + def getHTML(self): return DOM.getElementProperty(self.elem, "value") - - + + def getText(self): return DOM.getElementProperty(self.elem, "value") - - + + def initElement(self): self.onElementInitialized() - - + + def isBasicEditingSupported(self): return False - - + + def isExtendedEditingSupported(self): return False - - + + def setHTML(self, html): DOM.setElementProperty(self.elem, "value", html) - - + + def setText(self, text): DOM.setElementProperty(self.elem, "value", text) - - + + def uninitElement(self): pass - - + + def setFocus(self, focused): if (focused): Focus.focus(self.getElement()) @@ -79,18 +79,18 @@ def setFocus(self, focused): def createElement(self): return DOM.createTextArea() - - + + def hookEvents(self): print self, "hook events" DOM.sinkEvents(self.elem, Event.MOUSEEVENTS | Event.KEYEVENTS | Event.ONCHANGE | Event.ONCLICK | Event.FOCUSEVENTS) - - + + def onElementInitialized(self): print "onElementInitialized" self.hookEvents() - + def setCssStyling(self): pass diff --git a/library/pyjamas/ui/RichTextAreaImplStandard.browser.py b/library/pyjamas/ui/RichTextAreaImplStandard.browser.py index d54c71376..b9380b896 100644 --- a/library/pyjamas/ui/RichTextAreaImplStandard.browser.py +++ b/library/pyjamas/ui/RichTextAreaImplStandard.browser.py @@ -1,5 +1,5 @@ class RichTextAreaImplStandard (RichTextAreaImpl): - + def hookEvents(self): elem = self.elem; wnd = elem.contentWindow; diff --git a/library/pyjamas/ui/ScrollPanel.py b/library/pyjamas/ui/ScrollPanel.py index a936a5e40..4e9d2fb4c 100644 --- a/library/pyjamas/ui/ScrollPanel.py +++ b/library/pyjamas/ui/ScrollPanel.py @@ -46,7 +46,7 @@ def _getProps(self): # next three functions are part of the standard Builder API for panels def addIndexedItem(self, index, item): self.setWidget(item) - + def getWidgetIndex(self, index): return 0 diff --git a/library/pyjamas/ui/Sink.py b/library/pyjamas/ui/Sink.py index f91a0d9d5..dce94bde5 100644 --- a/library/pyjamas/ui/Sink.py +++ b/library/pyjamas/ui/Sink.py @@ -9,7 +9,7 @@ def __init__(self): self.vp_list=VerticalPanel() self.sinks=[] self.selectedSink=-1 - + self.initWidget(self.vp_list) self.setStyleName("ks-List") @@ -42,10 +42,10 @@ def setSinkSelection(self, name): class Sink(Composite): def __init__(self): Composite.__init__(self) - + def onHide(self): pass - + def onShow(self): pass @@ -71,7 +71,7 @@ def getInstance(self): if self.instance is None: self.instance = self.createInstance() return self.instance - + def getName(self): return self.name - + diff --git a/library/pyjamas/ui/SplitPanel.py b/library/pyjamas/ui/SplitPanel.py index 98f4036c9..404610abb 100644 --- a/library/pyjamas/ui/SplitPanel.py +++ b/library/pyjamas/ui/SplitPanel.py @@ -21,7 +21,7 @@ from __pyjamas__ import console from pyjamas import DOM from pyjamas import Window -from pyjamas import DeferredCommand +from pyjamas import DeferredCommand from pyjamas.EventController import EventGenerator from pyjamas.ui import GlassWidget from pyjamas.ui.SimplePanel import SimplePanel diff --git a/library/pyjamas/ui/TabBar.py b/library/pyjamas/ui/TabBar.py index c27d3e3c1..04c9622f0 100644 --- a/library/pyjamas/ui/TabBar.py +++ b/library/pyjamas/ui/TabBar.py @@ -73,11 +73,11 @@ def getTabCount(self): return self.panel.getWidgetCount() - 2 def getTabWidget(self, index): - if index >= self.getTabCount(): - return None - delPanel = self.panel.getWidget(index + 1) - focusablePanel = delPanel.getFocusablePanel() - widget = focusablePanel.getWidget() + if index >= self.getTabCount(): + return None + delPanel = self.panel.getWidget(index + 1) + focusablePanel = delPanel.getFocusablePanel() + widget = focusablePanel.getWidget() return widget def getTabHTML(self, index): diff --git a/library/pyjamas/ui/TabPanel.py b/library/pyjamas/ui/TabPanel.py index 88731b3ed..c92aabc3c 100644 --- a/library/pyjamas/ui/TabPanel.py +++ b/library/pyjamas/ui/TabPanel.py @@ -25,7 +25,7 @@ class TabPanel(PanelBase, Composite): def __init__(self, tabBar=None, **kwargs): self.children = [] # TODO: can self.children be used instead? - self.tab_names = {} + self.tab_names = {} self.deck = kwargs.pop('Deck', None) floatingtab = kwargs.pop('FloatingTab', False) if self.deck is None: diff --git a/library/pyjamas/ui/ToggleButton.py b/library/pyjamas/ui/ToggleButton.py index 1e8321300..011415c77 100644 --- a/library/pyjamas/ui/ToggleButton.py +++ b/library/pyjamas/ui/ToggleButton.py @@ -19,14 +19,14 @@ class ToggleButton (CustomButton): """ A ToggleButton is a stylish stateful button which allows the user to toggle between UP and DOWN states. - + CSS: .gwt-ToggleButton- up/down/up-hovering/down-hovering/up-disabled/down-disabled {.html-face} """ STYLENAME_DEFAULT = "gwt-ToggleButton" - - + + def __init__(self, upImageText = None, downImageText=None, handler = None, **kwargs): """ @@ -36,10 +36,10 @@ def __init__(self, upImageText = None, downImageText=None, handler = None, CustomButton.__init__(self, upImageText, downImageText, handler, **kwargs) - + def onClick(self, sender=None): self.toggleDown() CustomButton.onClick(self) - + Factory.registerClass('pyjamas.ui.ToggleButton', 'ToggleButton', ToggleButton) diff --git a/library/pyjamas/ui/Tooltip.py b/library/pyjamas/ui/Tooltip.py index 82049105e..cf62a19a3 100644 --- a/library/pyjamas/ui/Tooltip.py +++ b/library/pyjamas/ui/Tooltip.py @@ -18,7 +18,7 @@ def __init__(self, sender, offsetX, offsetY, contents, PopupPanel.__init__(self, True, **kwargs) self.show_delay = show_delay self.hide_delay = hide_delay - + if isinstance(contents, basestring): contents = HTML(contents) self.add(contents) @@ -33,10 +33,10 @@ def __init__(self, sender, offsetX, offsetY, contents, self.tooltip_show_timer = Timer(1, self) else: self.tooltip_show_timer = Timer(self.show_delay, self) - + def show(self): global tooltip_hide_timer - + # activate fast tooltips tooltip_hide_timer = Timer(self.hide_delay, self) PopupPanel.show(self) @@ -66,7 +66,7 @@ class TooltipListener: def __init__(self, text, show_delay = 1000, hide_delay = 5000, styleName = ""): if not styleName: styleName = self.DEFAULT_TOOLTIP_STYLE - + self.tooltip = None self.text = text self.styleName = styleName @@ -84,10 +84,10 @@ def onMouseLeave(self, sender): def onMouseMove(self, sender, x, y): pass - + def onMouseDown(self, sender, x, y): pass - + def onMouseUp(self, sender, x, y): pass @@ -112,6 +112,6 @@ def setOffsetY(self, offsetY): def hide(self): if self.tooltip is not None: self.tooltip.hide() - + Factory.registerClass('pyjamas.ui.Tooltip', 'Tooltip', Tooltip) diff --git a/library/pyjamas/ui/UIObject.py b/library/pyjamas/ui/UIObject.py index dfae6daa0..e1bc887c7 100644 --- a/library/pyjamas/ui/UIObject.py +++ b/library/pyjamas/ui/UIObject.py @@ -166,7 +166,7 @@ def addStyleName(self, style): def addStyleDependentName(self, styleSuffix): """Adds a secondary or dependent style name to this element. - For example if the primary stylename is gwt-TextBox, + For example if the primary stylename is gwt-TextBox, self.addStyleDependentName("readonly") will return gwt-TextBox-readonly. """ @@ -176,7 +176,7 @@ def removeStyleName(self, style): """Remove a style from the element associated with this UIObject. This is a CSS class name.""" self.setStyleName(self.element, style, False) - + def removeStyleDependentName(self, styleSuffix): """Remove a dependent style name by specifying the style name's suffix. """ diff --git a/library/pyjamas/ui/__init__.py b/library/pyjamas/ui/__init__.py index a348abb1c..923dc1807 100644 --- a/library/pyjamas/ui/__init__.py +++ b/library/pyjamas/ui/__init__.py @@ -55,7 +55,7 @@ def get_prop_widget_function_names(props): return get_list_columns(props, (PROP_FNAM,)) class Applier(object): - + _props = [] _elem_props = [] @@ -117,7 +117,7 @@ def _getElementProps(self): return self._elem_props def setDefaults(self, defaults): - divs = self.retrieveValues(wnames) + divs = self.retrieveValues(wnames) for p in get_prop_widget_function_names(self._getProps()): defaults[p[PROP_NAME]] = divs[p[PROP_FNAM]] @@ -130,7 +130,7 @@ def updateInstance(self, app_context): val = convert_to_type(val) if val else None args[p[PROP_FNAM]] = val - self.applyValues(**args) + self.applyValues(**args) def setElementProperties(self, context, elemProps): args = {} @@ -146,5 +146,5 @@ def setElementProperties(self, context, elemProps): continue args[p[ELPROP_FNAM]] = (context, val,) - self.applyValues(**args) + self.applyValues(**args) diff --git a/library/pyjamas/ui/horizsplitpanel.ie6.py b/library/pyjamas/ui/horizsplitpanel.ie6.py index 832c7b5c7..8503f23c0 100644 --- a/library/pyjamas/ui/horizsplitpanel.ie6.py +++ b/library/pyjamas/ui/horizsplitpanel.ie6.py @@ -4,13 +4,13 @@ /* * Copyright 2008 Google Inc. * Copyright 2009 Luke Kenneth Casson Leighton <lkcl@lkcl.net> - * + * * Licensed under the Apache License, Version 2.0 (the "License") you may not * use this file except in compliance with the License. You may obtain a copy of * the License at - * + * * http:#www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the @@ -24,7 +24,7 @@ class ImplHorizontalSplitPanel: """ def __init__(self, panel): - + self.panel = panel self.isResizeInProgress = False self.splitPosition = 0 @@ -34,11 +34,11 @@ def __init__(self, panel): # Prevents inherited text-align settings from interfering with the # panel's layout. The setting we choose must be bidi-sensitive, # as left-alignment is the default with LTR directionality, and - # right-alignment is the default with RTL directionality. + # right-alignment is the default with RTL directionality. if True: # TODO (LocaleInfo.getCurrentLocale().isRTL()) { DOM.setStyleAttribute(elem, "textAlign", "right") else: - DOM.setStyleAttribute(elem, "textAlign", "left") + DOM.setStyleAttribute(elem, "textAlign", "left") DOM.setStyleAttribute(elem, "position", "relative") @@ -52,8 +52,8 @@ def __init__(self, panel): self.panel.expandToFitParentUsingPercentages(panel.container) if True: # TODO (LocaleInfo.getCurrentLocale().isRTL()): - # Snap the left pane to the left edge of the container. We - # only need to do this when layout is RTL if we don't, the + # Snap the left pane to the left edge of the container. We + # only need to do this when layout is RTL if we don't, the # left pane will overlap the right pane. panel.setLeft(panel.getWidgetElement(0), "0px") @@ -102,19 +102,19 @@ def setSplitPositionUsingPixels(self, px): # Set the width of the right side. self.panel.setElemWidth(self.panel.getWidgetElement(1), newRightWidth + "px") - # Move the splitter to the right edge of the left element. - self.panel.setLeft(splitElem, px + "px") + # Move the splitter to the right edge of the left element. + self.panel.setLeft(splitElem, px + "px") - # Update the width of the left side + # Update the width of the left side if (px == 0): - # This takes care of a qurky RTL layout bug with IE6. + # This takes care of a qurky RTL layout bug with IE6. # During DOM construction and layout, onResize events - # are fired, and this method is called with px == 0. + # are fired, and this method is called with px == 0. # If one tries to set the width of the 0 element to # before layout completes, the 1 element will # appear to be blanked out. - + DeferredCommand.add(self) else: self.panel.setElemWidth(self.panel.getWidgetElement(0), px + "px") @@ -146,5 +146,5 @@ def onResize(self): self.panel.setElemHeight(rightElem, height) self.panel.setElemHeight(self.panel.getSplitElement(), height) self.panel.setElemHeight(leftElem, height) - self.setSplitPositionUsingPixels(self.panel.getOffsetWidth(leftElem)) + self.setSplitPositionUsingPixels(self.panel.getOffsetWidth(leftElem)) diff --git a/library/pyjamas/ui/horizsplitpanel.safari.py b/library/pyjamas/ui/horizsplitpanel.safari.py index 540971318..db9c7be87 100644 --- a/library/pyjamas/ui/horizsplitpanel.safari.py +++ b/library/pyjamas/ui/horizsplitpanel.safari.py @@ -4,13 +4,13 @@ /* * Copyright 2008 Google Inc. * Copyright 2009 Luke Kenneth Casson Leighton <lkcl@lkcl.net> - * + * * Licensed under the Apache License, Version 2.0 (the "License") you may not * use this file except in compliance with the License. You may obtain a copy of * the License at - * + * * http:#www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the @@ -20,12 +20,12 @@ """ class ImplHorizontalSplitPanel: - """ + """ The Safari implementation which owes its existence entirely to a single WebKit bug: http:#bugs.webkit.org/show_bug.cgi?id=9137. """ def __init__(self, panel): - + fullSize = "100%" ImplHorizontalSplitPanel.__init__(self, panel) self.panel.setElemHeight(self.panel.container, fullSize) diff --git a/pgen/astgen.skult.py b/pgen/astgen.skult.py index c6179d22b..a3fdb3241 100644 --- a/pgen/astgen.skult.py +++ b/pgen/astgen.skult.py @@ -106,7 +106,7 @@ def _gen_init(self, buf): if self.args: print >> buf, " def __init__ (self, %s, lineno):\n" % (self.args) else: - print >> buf, " def __init__(self, lineno):\n" + print >> buf, " def __init__(self, lineno):\n" print >>buf, " self.nodeName = \"%s\";" % self.name if self.argnames: for name in self.argnames: @@ -222,7 +222,7 @@ def main(): """ ### PROLOGUE # abstract syntax node definitions -# +# # This file is automatically generated by pgen/astgen.py OP_ASSIGN = 'OP_ASSIGN'; diff --git a/pgen/generate_pyjs_parsers.py b/pgen/generate_pyjs_parsers.py index 74254537c..ea4ae7b86 100644 --- a/pgen/generate_pyjs_parsers.py +++ b/pgen/generate_pyjs_parsers.py @@ -33,7 +33,7 @@ out = g_templ.substitute(gen_date=gen_date, python_version=python_version, - grammar_attrs_assign=attrs_assign_str, + grammar_attrs_assign=attrs_assign_str, opmap_assign=opmap_assign) out_f = open('grammar2x.py', 'w') diff --git a/pgen/lib2to3/compiler/parser.py b/pgen/lib2to3/compiler/parser.py index 5ee491bba..12e591896 100644 --- a/pgen/lib2to3/compiler/parser.py +++ b/pgen/lib2to3/compiler/parser.py @@ -12,4 +12,4 @@ def suite(text): # dummy def st2tuple(tree, line_info=1): return tree - + diff --git a/pgen/lib2to3/compiler/pyassem.py b/pgen/lib2to3/compiler/pyassem.py index 8e8fb2e2e..42acf5c58 100644 --- a/pgen/lib2to3/compiler/pyassem.py +++ b/pgen/lib2to3/compiler/pyassem.py @@ -141,7 +141,7 @@ def fixupOrderHonorNext(self, blocks, default_next): for j, b in l: del blocks[index[b]] # Insert the chain in the proper location - blocks = blocks[:i] + [cur] + [chain] + blocks[i + 1:] + blocks = blocks[:i] + [cur] + [chain] + blocks[i + 1:] # Finally, re-compute the block indexes for i in range(len(blocks)): index[blocks[i]] = i diff --git a/pgen/test_parse.py b/pgen/test_parse.py index 8df04eef0..2831bb0a5 100644 --- a/pgen/test_parse.py +++ b/pgen/test_parse.py @@ -32,7 +32,7 @@ def compare_compilers(fname): ys1 = getAststr(compiler.ast, x1) except SyntaxError: ys1 = traceback.format_exc(limit=0) - + if test_pyjs: try: y = test_compiler.parseFile(fname) diff --git a/pygtkweb/demos/001-gpython.py b/pygtkweb/demos/001-gpython.py index 44551b53c..12df6bf34 100644 --- a/pygtkweb/demos/001-gpython.py +++ b/pygtkweb/demos/001-gpython.py @@ -72,7 +72,7 @@ def attr_matches (self, text): words = walk_class (obj) else: words = dir(eval(expr, self.locals)) - + matches = [] n = len(attr) for word in words: @@ -87,7 +87,7 @@ class GtkInterpreter (threading.Thread): GTK timeout callback. """ TIMEOUT = 100 # Millisecond interval between timeouts. - + def __init__ (self): threading.Thread.__init__ (self) self.ready = threading.Condition () @@ -119,18 +119,18 @@ def code_exec (self): self.cmd = self.cmd + self.new_cmd self.new_cmd = None try: - code = codeop.compile_command (self.cmd[:-1]) - if code: + code = codeop.compile_command (self.cmd[:-1]) + if code: self.cmd = '' exec (code, self.globs, self.locs) self.completer.update (self.locs) except Exception: traceback.print_exc () - self.cmd = '' - + self.cmd = '' + self.ready.release() - return 1 - + return 1 + def feed (self, code): """Feed a line of code to the thread. This function will block until the code checked by the GTK thread. @@ -138,12 +138,12 @@ def feed (self, code): Returns false if deferring execution until complete block available. """ if (not code) or (code[-1]<>'\n'): code = code +'\n' # raw_input strips newline - self.completer.update (self.locs) + self.completer.update (self.locs) self.ready.acquire() self.new_cmd = code self.ready.wait () # Wait until processed in timeout interval self.ready.release () - + return not self.cmd def kill (self): @@ -152,7 +152,7 @@ def kill (self): self._kill=1 self.ready.release() self.join() - + # Read user input in a loop, and send each line to the interpreter thread. def signal_handler (*args): @@ -162,7 +162,7 @@ def signal_handler (*args): if __name__=="__main__": signal.signal (signal.SIGINT, signal_handler) signal.signal (signal.SIGSEGV, signal_handler) - + prompt = '>>> ' interpreter = GtkInterpreter () interpreter.start () diff --git a/pygtkweb/demos/005-packbox.py b/pygtkweb/demos/005-packbox.py index 9235e777e..16a09799d 100644 --- a/pygtkweb/demos/005-packbox.py +++ b/pygtkweb/demos/005-packbox.py @@ -64,29 +64,29 @@ def __init__(self, which): # behavior self.window.connect("delete_event", self.delete_event) self.window.set_border_width(10) - + # We create a vertical box (vbox) to pack the horizontal boxes into. # This allows us to stack the horizontal boxes filled with buttons one # on top of the other in this vbox. box1 = gtk.VBox(False, 0) - + # which example to show. These correspond to the pictures above. if which == 1: # create a new label. label = gtk.Label("HBox(False, 0)") - + # Align the label to the left side. We'll discuss this method # and others in the section on Widget Attributes. label.set_alignment(0, 0) - # Pack the label into the vertical box (vbox box1). Remember that + # Pack the label into the vertical box (vbox box1). Remember that # widgets added to a vbox will be packed one on top of the other in # order. box1.pack_start(label, False, False, 0) - + # Show the label label.show() - + # Call our make box function - homogeneous = False, spacing = 0, # expand = False, fill = False, padding = 0 box2 = make_box(False, 0, False, False, 0) @@ -98,38 +98,38 @@ def __init__(self, which): box2 = make_box(False, 0, True, False, 0) box1.pack_start(box2, False, False, 0) box2.show() - + # Args are: homogeneous, spacing, expand, fill, padding box2 = make_box(False, 0, True, True, 0) box1.pack_start(box2, False, False, 0) box2.show() - - # Creates a separator, we'll learn more about these later, + + # Creates a separator, we'll learn more about these later, # but they are quite simple. separator = gtk.HSeparator() - + # Pack the separator into the vbox. Remember each of these # widgets is being packed into a vbox, so they'll be stacked # vertically. box1.pack_start(separator, False, True, 5) separator.show() - + # Create another new label, and show it. label = gtk.Label("HBox(True, 0)") label.set_alignment(0, 0) box1.pack_start(label, False, False, 0) label.show() - + # Args are: homogeneous, spacing, expand, fill, padding box2 = make_box(True, 0, True, False, 0) box1.pack_start(box2, False, False, 0) box2.show() - + # Args are: homogeneous, spacing, expand, fill, padding box2 = make_box(True, 0, True, True, 0) box1.pack_start(box2, False, False, 0) box2.show() - + # Another new separator. separator = gtk.HSeparator() # The last 3 arguments to pack_start are: @@ -137,44 +137,44 @@ def __init__(self, which): box1.pack_start(separator, False, True, 5) separator.show() elif which == 2: - # Create a new label, remember box1 is a vbox as created + # Create a new label, remember box1 is a vbox as created # near the beginning of __init__() label = gtk.Label("HBox(False, 10)") label.set_alignment( 0, 0) box1.pack_start(label, False, False, 0) label.show() - + # Args are: homogeneous, spacing, expand, fill, padding box2 = make_box(False, 10, True, False, 0) box1.pack_start(box2, False, False, 0) box2.show() - + # Args are: homogeneous, spacing, expand, fill, padding box2 = make_box(False, 10, True, True, 0) box1.pack_start(box2, False, False, 0) box2.show() - + separator = gtk.HSeparator() # The last 3 arguments to pack_start are: # expand, fill, padding. box1.pack_start(separator, False, True, 5) separator.show() - + label = gtk.Label("HBox(False, 0)") label.set_alignment(0, 0) box1.pack_start(label, False, False, 0) label.show() - + # Args are: homogeneous, spacing, expand, fill, padding box2 = make_box(False, 0, True, False, 10) box1.pack_start(box2, False, False, 0) box2.show() - + # Args are: homogeneous, spacing, expand, fill, padding box2 = make_box(False, 0, True, True, 10) box1.pack_start(box2, False, False, 0) box2.show() - + separator = gtk.HSeparator() # The last 3 arguments to pack_start are: # expand, fill, padding. @@ -194,31 +194,31 @@ def __init__(self, which): box2.pack_end(label, False, False, 0) # Show the label. label.show() - + # Pack box2 into box1 box1.pack_start(box2, False, False, 0) box2.show() - + # A separator for the bottom. separator = gtk.HSeparator() - + # This explicitly sets the separator to 400 pixels wide by 5 # pixels high. This is so the hbox we created will also be 400 # pixels wide, and the "end" label will be separated from the # other labels in the hbox. Otherwise, all the widgets in the # hbox would be packed as close together as possible. separator.set_size_request(400, 5) - # pack the separator into the vbox (box1) created near the start + # pack the separator into the vbox (box1) created near the start # of __init__() box1.pack_start(separator, False, True, 5) separator.show() - + # Create another new hbox.. remember we can use as many as we need! quitbox = gtk.HBox(False, 0) - + # Our quit button. button = gtk.Button("Quit") - + # Setup the signal to terminate the program when the button is clicked button.connect("clicked", lambda w: gtk.main_quit()) # Pack the button into the quitbox. @@ -227,15 +227,15 @@ def __init__(self, which): quitbox.pack_start(button, True, False, 0) # pack the quitbox into the vbox (box1) box1.pack_start(quitbox, False, False, 0) - + # Pack the vbox (box1) which now contains all our widgets, into the # main window. self.window.add(box1) - + # And show everything left button.show() quitbox.show() - + box1.show() # Showing the window last so everything pops up at once. self.window.show() @@ -244,7 +244,7 @@ def main(): # And of course, our main loop. gtk.main() # Control returns here when main_quit() is called - return 0 + return 0 if __name__ =="__main__": if len(sys.argv) != 2: diff --git a/pygtkweb/demos/007-buttons.py b/pygtkweb/demos/007-buttons.py index c494f40ed..6a9881f34 100644 --- a/pygtkweb/demos/007-buttons.py +++ b/pygtkweb/demos/007-buttons.py @@ -67,7 +67,7 @@ def __init__(self): def main(): gtk.main() - return 0 + return 0 if __name__ == "__main__": Buttons() diff --git a/pygtkweb/demos/008-togglebutton.py b/pygtkweb/demos/008-togglebutton.py index ca2bbd1af..f9c4ae51f 100644 --- a/pygtkweb/demos/008-togglebutton.py +++ b/pygtkweb/demos/008-togglebutton.py @@ -78,7 +78,7 @@ def __init__(self): def main(): gtk.main() - return 0 + return 0 if __name__ == "__main__": ToggleButton() diff --git a/pygtkweb/demos/010-radiobuttons.py b/pygtkweb/demos/010-radiobuttons.py index db0f97980..94a2d2731 100644 --- a/pygtkweb/demos/010-radiobuttons.py +++ b/pygtkweb/demos/010-radiobuttons.py @@ -16,7 +16,7 @@ def close_application(self, widget, event, data=None): def __init__(self): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) - + self.window.connect("delete_event", self.close_application) self.window.set_title("radio buttons") @@ -67,7 +67,7 @@ def __init__(self): def main(): gtk.main() - return 0 + return 0 if __name__ == "__main__": RadioButtons() diff --git a/pygtkweb/demos/012-label.py b/pygtkweb/demos/012-label.py index bb519dce1..ba4e31f97 100644 --- a/pygtkweb/demos/012-label.py +++ b/pygtkweb/demos/012-label.py @@ -22,20 +22,20 @@ def __init__(self): label = gtk.Label("This is a Normal label") frame.add(label) vbox.pack_start(frame, False, False, 0) - + frame = gtk.Frame("Multi-line Label") label = gtk.Label("This is a Multi-line label.\nSecond line\n" "Third line") frame.add(label) vbox.pack_start(frame, False, False, 0) - + frame = gtk.Frame("Left Justified Label") label = gtk.Label("This is a Left-Justified\n" "Multi-line label.\nThird line") label.set_justify(gtk.JUSTIFY_LEFT) frame.add(label) vbox.pack_start(frame, False, False, 0) - + frame = gtk.Frame("Right Justified Label") label = gtk.Label("This is a Right-Justified\nMulti-line label.\n" "Fourth line, (j/k)") @@ -59,7 +59,7 @@ def __init__(self): label.set_line_wrap(True) frame.add(label) vbox.pack_start(frame, False, False, 0) - + frame = gtk.Frame("Filled, wrapped label") label = gtk.Label("This is an example of a line-wrapped, filled label. " "It should be taking " @@ -75,7 +75,7 @@ def __init__(self): label.set_line_wrap(True) frame.add(label) vbox.pack_start(frame, False, False, 0) - + frame = gtk.Frame("Underlined label") label = gtk.Label("This label is underlined!\n" "This one is underlined in quite a funky fashion") diff --git a/pygtkweb/demos/013-arrow.py b/pygtkweb/demos/013-arrow.py index aee8df089..7718d1ca0 100644 --- a/pygtkweb/demos/013-arrow.py +++ b/pygtkweb/demos/013-arrow.py @@ -42,13 +42,13 @@ def __init__(self): button = create_arrow_button(gtk.ARROW_DOWN, gtk.SHADOW_OUT) box.pack_start(button, False, False, 3) - + button = create_arrow_button(gtk.ARROW_LEFT, gtk.SHADOW_ETCHED_IN) box.pack_start(button, False, False, 3) - + button = create_arrow_button(gtk.ARROW_RIGHT, gtk.SHADOW_ETCHED_OUT) box.pack_start(button, False, False, 3) - + window.show() def main(): diff --git a/pygtkweb/demos/014-tooltip.py b/pygtkweb/demos/014-tooltip.py index 5b9c4bfb4..16301e18f 100644 --- a/pygtkweb/demos/014-tooltip.py +++ b/pygtkweb/demos/014-tooltip.py @@ -47,11 +47,11 @@ def __init__(self): button = create_arrow_button(gtk.ARROW_DOWN, gtk.SHADOW_OUT) box.pack_start(button, False, False, 3) self.tooltips.set_tip(button, "SHADOW_OUT") - + button = create_arrow_button(gtk.ARROW_LEFT, gtk.SHADOW_ETCHED_IN) box.pack_start(button, False, False, 3) self.tooltips.set_tip(button, "SHADOW_ETCHED_IN") - + button = create_arrow_button(gtk.ARROW_RIGHT, gtk.SHADOW_ETCHED_OUT) box.pack_start(button, False, False, 3) self.tooltips.set_tip(button, "SHADOW_ETCHED_OUT") diff --git a/pygtkweb/demos/015-progressbar.py b/pygtkweb/demos/015-progressbar.py index d4e420d09..741be4e04 100644 --- a/pygtkweb/demos/015-progressbar.py +++ b/pygtkweb/demos/015-progressbar.py @@ -66,7 +66,7 @@ def __init__(self): vbox.set_border_width(10) self.window.add(vbox) vbox.show() - + # Create a centering alignment object align = gtk.Alignment(0.5, 0.5, 0, 0) vbox.pack_start(align, False, False, 5) diff --git a/pygtkweb/demos/016-images.py b/pygtkweb/demos/016-images.py index ec1973876..780a6ddf6 100644 --- a/pygtkweb/demos/016-images.py +++ b/pygtkweb/demos/016-images.py @@ -39,7 +39,7 @@ def __init__(self): button.show() hbox.pack_start(button) button.connect("clicked", self.button_clicked, "1") - + # create several images with data from files and load images into # buttons image = gtk.Image() diff --git a/pygtkweb/demos/018-wheelbarrow.py b/pygtkweb/demos/018-wheelbarrow.py index e957646b2..69818b5af 100644 --- a/pygtkweb/demos/018-wheelbarrow.py +++ b/pygtkweb/demos/018-wheelbarrow.py @@ -155,7 +155,7 @@ def __init__(self): # This masks out everything except for the image itself window.shape_combine_mask(mask, 0, 0) - + # show the window window.set_position(gtk.WIN_POS_CENTER_ALWAYS) window.show() diff --git a/pygtkweb/demos/019-rulers.py b/pygtkweb/demos/019-rulers.py index fd816318f..2fb5086d0 100644 --- a/pygtkweb/demos/019-rulers.py +++ b/pygtkweb/demos/019-rulers.py @@ -42,7 +42,7 @@ def motion_notify(ruler, event): area.connect_object("motion_notify_event", motion_notify, hrule) table.attach(hrule, 1, 2, 0, 1, gtk.EXPAND|gtk.SHRINK|gtk.FILL, gtk.FILL, 0, 0 ) - + # The vertical ruler goes on the left. As the mouse moves across # the drawing area, a motion_notify_event is passed to the # appropriate event handler for the ruler. diff --git a/pygtkweb/demos/020-statusbar.py b/pygtkweb/demos/020-statusbar.py index cf58a52d2..d0896e1c7 100644 --- a/pygtkweb/demos/020-statusbar.py +++ b/pygtkweb/demos/020-statusbar.py @@ -24,12 +24,12 @@ def __init__(self): window.set_size_request(200, 100) window.set_title("PyGTK Statusbar Example") window.connect("delete_event", lambda w,e: gtk.main_quit()) - + vbox = gtk.VBox(False, 1) window.add(vbox) vbox.show() - - self.status_bar = gtk.Statusbar() + + self.status_bar = gtk.Statusbar() vbox.pack_start(self.status_bar, True, True, 0) self.status_bar.show() @@ -38,12 +38,12 @@ def __init__(self): button = gtk.Button("push item") button.connect("clicked", self.push_item, context_id) vbox.pack_start(button, True, True, 2) - button.show() + button.show() button = gtk.Button("pop last item") button.connect("clicked", self.pop_item, context_id) vbox.pack_start(button, True, True, 2) - button.show() + button.show() # always display the window as the last step so it all splashes on # the screen at once. diff --git a/pygtkweb/demos/021-entry.py b/pygtkweb/demos/021-entry.py index 9fb5b201f..c047255a0 100644 --- a/pygtkweb/demos/021-entry.py +++ b/pygtkweb/demos/021-entry.py @@ -40,19 +40,19 @@ def __init__(self): hbox = gtk.HBox(False, 0) vbox.add(hbox) hbox.show() - + check = gtk.CheckButton("Editable") hbox.pack_start(check, True, True, 0) check.connect("toggled", self.entry_toggle_editable, entry) check.set_active(True) check.show() - + check = gtk.CheckButton("Visible") hbox.pack_start(check, True, True, 0) check.connect("toggled", self.entry_toggle_visibility, entry) check.set_active(True) check.show() - + button = gtk.Button(stock=gtk.STOCK_CLOSE) button.connect("clicked", lambda w: gtk.main_quit()) vbox.pack_start(button, True, True, 0) diff --git a/pygtkweb/demos/022-spinbutton.py b/pygtkweb/demos/022-spinbutton.py index 9e9076a15..02f164845 100644 --- a/pygtkweb/demos/022-spinbutton.py +++ b/pygtkweb/demos/022-spinbutton.py @@ -35,7 +35,7 @@ def __init__(self): frame = gtk.Frame("Not accelerated") main_vbox.pack_start(frame, True, True, 0) - + vbox = gtk.VBox(False, 0) vbox.set_border_width(5) frame.add(vbox) @@ -43,22 +43,22 @@ def __init__(self): # Day, month, year spinners hbox = gtk.HBox(False, 0) vbox.pack_start(hbox, True, True, 5) - + vbox2 = gtk.VBox(False, 0) hbox.pack_start(vbox2, True, True, 5) label = gtk.Label("Day :") label.set_alignment(0, 0.5) vbox2.pack_start(label, False, True, 0) - + adj = gtk.Adjustment(1.0, 1.0, 31.0, 1.0, 5.0, 0.0) spinner = gtk.SpinButton(adj, 0, 0) spinner.set_wrap(True) vbox2.pack_start(spinner, False, True, 0) - + vbox2 = gtk.VBox(False, 0) hbox.pack_start(vbox2, True, True, 5) - + label = gtk.Label("Month :") label.set_alignment(0, 0.5) vbox2.pack_start(label, False, True, 0) @@ -67,56 +67,56 @@ def __init__(self): spinner = gtk.SpinButton(adj, 0, 0) spinner.set_wrap(True) vbox2.pack_start(spinner, False, True, 0) - + vbox2 = gtk.VBox(False, 0) hbox.pack_start(vbox2, True, True, 5) - + label = gtk.Label("Year :") label.set_alignment(0, 0.5) vbox2.pack_start(label, False, True, 0) - + adj = gtk.Adjustment(1998.0, 0.0, 2100.0, 1.0, 100.0, 0.0) spinner = gtk.SpinButton(adj, 0, 0) spinner.set_wrap(False) spinner.set_size_request(55, -1) vbox2.pack_start(spinner, False, True, 0) - + frame = gtk.Frame("Accelerated") main_vbox.pack_start(frame, True, True, 0) - + vbox = gtk.VBox(False, 0) vbox.set_border_width(5) frame.add(vbox) - + hbox = gtk.HBox(False, 0) vbox.pack_start(hbox, False, True, 5) - + vbox2 = gtk.VBox(False, 0) hbox.pack_start(vbox2, True, True, 5) - + label = gtk.Label("Value :") label.set_alignment(0, 0.5) vbox2.pack_start(label, False, True, 0) - + adj = gtk.Adjustment(0.0, -10000.0, 10000.0, 0.5, 100.0, 0.0) spinner1 = gtk.SpinButton(adj, 1.0, 2) spinner1.set_wrap(True) spinner1.set_size_request(100, -1) vbox2.pack_start(spinner1, False, True, 0) - + vbox2 = gtk.VBox(False, 0) hbox.pack_start(vbox2, True, True, 5) - + label = gtk.Label("Digits :") label.set_alignment(0, 0.5) vbox2.pack_start(label, False, True, 0) - + adj = gtk.Adjustment(2, 1, 5, 1, 1, 0) spinner2 = gtk.SpinButton(adj, 0.0, 0) spinner2.set_wrap(True) adj.connect("value_changed", self.change_digits, spinner2, spinner1) vbox2.pack_start(spinner2, False, True, 0) - + hbox = gtk.HBox(False, 0) vbox.pack_start(hbox, False, True, 5) @@ -124,32 +124,32 @@ def __init__(self): button.connect("clicked", self.toggle_snap, spinner1) vbox.pack_start(button, True, True, 0) button.set_active(True) - + button = gtk.CheckButton("Numeric only input mode") button.connect("clicked", self.toggle_numeric, spinner1) vbox.pack_start(button, True, True, 0) button.set_active(True) - + val_label = gtk.Label("") - + hbox = gtk.HBox(False, 0) vbox.pack_start(hbox, False, True, 5) button = gtk.Button("Value as Int") button.connect("clicked", self.get_value, 1, spinner1, spinner2, val_label) hbox.pack_start(button, True, True, 5) - + button = gtk.Button("Value as Float") button.connect("clicked", self.get_value, 2, spinner1, spinner2, val_label) hbox.pack_start(button, True, True, 5) - + vbox.pack_start(val_label, True, True, 0) val_label.set_text("0") - + hbox = gtk.HBox(False, 0) main_vbox.pack_start(hbox, False, True, 0) - + button = gtk.Button("Close") button.connect("clicked", lambda w: gtk.main_quit()) hbox.pack_start(button, True, True, 5) diff --git a/pygtkweb/demos/023-calendar.py b/pygtkweb/demos/023-calendar.py index f0f3099d0..c357723b9 100644 --- a/pygtkweb/demos/023-calendar.py +++ b/pygtkweb/demos/023-calendar.py @@ -32,7 +32,7 @@ class CalendarExample: calendar_show_header = 0 calendar_show_days = 1 - calendar_month_change = 2 + calendar_month_change = 2 calendar_show_week = 3 def calendar_date_to_string(self): @@ -107,18 +107,18 @@ def calendar_font_selection_ok(self, button): self.font = self.font_dialog.get_font_name() if self.window: font_desc = pango.FontDescription(self.font) - if font_desc: + if font_desc: self.window.modify_font(font_desc) def calendar_select_font(self, button): if not self.font_dialog: window = gtk.FontSelectionDialog("Font Selection Dialog") self.font_dialog = window - + window.set_position(gtk.WIN_POS_MOUSE) - + window.connect("destroy", self.font_dialog_destroyed) - + window.ok_button.connect("clicked", self.calendar_font_selection_ok) window.cancel_button.connect_object("clicked", @@ -189,8 +189,8 @@ def __init__(self): vbox2 = gtk.VBox(False, self.DEF_PAD) hbox.pack_start(vbox2, False, False, self.DEF_PAD) - - # Build the Right frame with the flags in + + # Build the Right frame with the flags in frame = gtk.Frame("Flags") vbox2.pack_start(frame, True, True, self.DEF_PAD) vbox3 = gtk.VBox(True, self.DEF_PAD_SMALL) @@ -202,7 +202,7 @@ def __init__(self): vbox3.pack_start(toggle, True, True, 0) self.flag_checkboxes[i] = toggle - # Build the right font-button + # Build the right font-button button = gtk.Button("Font...") button.connect("clicked", self.calendar_select_font) vbox2.pack_start(button, False, False, 0) @@ -213,7 +213,7 @@ def __init__(self): vbox2 = gtk.VBox(True, self.DEF_PAD_SMALL) frame.add(vbox2) - + hbox = gtk.HBox (False, 3) vbox2.pack_start(hbox, False, True, 0) label = gtk.Label("Signal:") diff --git a/pygtkweb/demos/024-colorsel.py b/pygtkweb/demos/024-colorsel.py index dfe31c3d3..59838b093 100644 --- a/pygtkweb/demos/024-colorsel.py +++ b/pygtkweb/demos/024-colorsel.py @@ -66,7 +66,7 @@ def __init__(self): # Attach to the "delete" and "destroy" events so we can exit window.connect("delete_event", self.destroy_window) - + # Create drawingarea, set size and catch button events self.drawingarea = gtk.DrawingArea() @@ -75,12 +75,12 @@ def __init__(self): self.drawingarea.set_size_request(200, 200) self.drawingarea.set_events(gtk.gdk.BUTTON_PRESS_MASK) self.drawingarea.connect("event", self.area_event) - + # Add drawingarea to window, then show them both window.add(self.drawingarea) self.drawingarea.show() window.show() - + def main(): gtk.main() return 0 diff --git a/pygtkweb/demos/025-filesel.py b/pygtkweb/demos/025-filesel.py index 3223642b3..a2cec4be3 100644 --- a/pygtkweb/demos/025-filesel.py +++ b/pygtkweb/demos/025-filesel.py @@ -21,15 +21,15 @@ def __init__(self): self.filew.connect("destroy", self.destroy) # Connect the ok_button to file_ok_sel method self.filew.ok_button.connect("clicked", self.file_ok_sel) - + # Connect the cancel_button to destroy the widget self.filew.cancel_button.connect("clicked", lambda w: self.filew.destroy()) - + # Lets set the filename, as if this were a save dialog, # and we are giving a default filename self.filew.set_filename("penguin.png") - + self.filew.show() def main(): diff --git a/pygtkweb/demos/027-fixed.py b/pygtkweb/demos/027-fixed.py index 5dc87b2bc..8114b0f40 100644 --- a/pygtkweb/demos/027-fixed.py +++ b/pygtkweb/demos/027-fixed.py @@ -12,7 +12,7 @@ class FixedExample: def move_button(self, widget): self.x = (self.x+30)%300 self.y = (self.y+50)%300 - self.fixed.move(widget, self.x, self.y) + self.fixed.move(widget, self.x, self.y) def __init__(self): self.x = 50 @@ -22,9 +22,9 @@ def __init__(self): window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.set_title("Fixed Container") - # Here we connect the "destroy" event to a signal handler + # Here we connect the "destroy" event to a signal handler window.connect("destroy", lambda w: gtk.main_quit()) - + # Sets the border width of the window. window.set_border_width(10) @@ -32,18 +32,18 @@ def __init__(self): self.fixed = gtk.Fixed() window.add(self.fixed) self.fixed.show() - + for i in range(1, 4): # Creates a new button with the label "Press me" button = gtk.Button("Press me") - + # When the button receives the "clicked" signal, it will call the # method move_button(). button.connect("clicked", self.move_button) - + # This packs the button into the fixed containers window. self.fixed.put(button, i*50, i*50) - + # The final step is to display this newly created widget. button.show() diff --git a/pygtkweb/demos/028-layout.py b/pygtkweb/demos/028-layout.py index 4b50a14e0..008ab6ea8 100644 --- a/pygtkweb/demos/028-layout.py +++ b/pygtkweb/demos/028-layout.py @@ -42,7 +42,7 @@ def __init__(self): gtk.FILL|gtk.SHRINK, 0, 0) hScrollbar = gtk.HScrollbar(None) table.attach(hScrollbar, 0, 1, 1, 2, gtk.FILL|gtk.SHRINK, - gtk.FILL|gtk.SHRINK, 0, 0) + gtk.FILL|gtk.SHRINK, 0, 0) # tell the scrollbars to use the layout widget's adjustments vAdjust = self.layout.get_vadjustment() vScrollbar.set_adjustment(vAdjust) diff --git a/pygtkweb/demos/029-frame.py b/pygtkweb/demos/029-frame.py index 5ae8537e7..31bb57671 100644 --- a/pygtkweb/demos/029-frame.py +++ b/pygtkweb/demos/029-frame.py @@ -12,7 +12,7 @@ def __init__(self): window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.set_title("Frame Example") - # Here we connect the "destroy" event to a signal handler + # Here we connect the "destroy" event to a signal handler window.connect("destroy", lambda w: gtk.main_quit()) window.set_size_request(300, 300) @@ -32,7 +32,7 @@ def __init__(self): # Set the style of the frame frame.set_shadow_type(gtk.SHADOW_ETCHED_OUT) frame.show() - + # Display the window window.show() diff --git a/pygtkweb/demos/031-paned.py b/pygtkweb/demos/031-paned.py index 2a388658a..c57a3d717 100644 --- a/pygtkweb/demos/031-paned.py +++ b/pygtkweb/demos/031-paned.py @@ -29,7 +29,7 @@ def create_list(self): tree_view.append_column(column) return scrolled_window - + # Add some text to our text widget - this is a callback that is invoked # when our window is realized. We could also force our window to be # realized with GtkWidget.realize, but it would have to be part of a @@ -45,7 +45,7 @@ def insert_text(self, buffer): "great - clear but cold, and there are lots of fun sights.\n" "Sojourner says hi. See you soon.\n" " -Path\n") - + # Create a scrolled text area that displays a "message" def create_text(self): view = gtk.TextView() @@ -56,7 +56,7 @@ def create_text(self): self.insert_text(buffer) scrolled_window.show_all() return scrolled_window - + def __init__(self): window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.set_title("Paned Windows") diff --git a/pygtkweb/demos/032-scrolledwin.py b/pygtkweb/demos/032-scrolledwin.py index f4cf5d687..7ce1b4b90 100644 --- a/pygtkweb/demos/032-scrolledwin.py +++ b/pygtkweb/demos/032-scrolledwin.py @@ -12,7 +12,7 @@ def destroy(self, widget): def __init__(self): # Create a new dialog window for the scrolled window to be - # packed into. + # packed into. window = gtk.Dialog() window.connect("destroy", self.destroy) window.set_title("ScrolledWindow example") @@ -33,7 +33,7 @@ def __init__(self): # The dialog window is created with a vbox packed into it. window.vbox.pack_start(scrolled_window, True, True, 0) scrolled_window.show() - + # create a table of 10 by 10 squares. table = gtk.Table(10, 10, False) diff --git a/pygtkweb/demos/034-toolbar.py b/pygtkweb/demos/034-toolbar.py index fd5917198..6489ddb1e 100644 --- a/pygtkweb/demos/034-toolbar.py +++ b/pygtkweb/demos/034-toolbar.py @@ -17,22 +17,22 @@ def delete_event(self, widget, event=None): # check which one is active and set the style of the toolbar # accordingly def radio_event(self, widget, toolbar): - if self.text_button.get_active(): + if self.text_button.get_active(): toolbar.set_style(gtk.TOOLBAR_TEXT) elif self.icon_button.get_active(): toolbar.set_style(gtk.TOOLBAR_ICONS) elif self.both_button.get_active(): toolbar.set_style(gtk.TOOLBAR_BOTH) - # even easier, just check given toggle button and enable/disable + # even easier, just check given toggle button and enable/disable # tooltips def toggle_event(self, widget, toolbar): toolbar.set_tooltips(widget.get_active()) def __init__(self): # Here is our main window (a dialog) and a handle for the handlebox - # Ok, we need a toolbar, an icon with a mask (one for all of - # the buttons) and an icon widget to put this icon in (but + # Ok, we need a toolbar, an icon with a mask (one for all of + # the buttons) and an icon widget to put this icon in (but # we'll create a separate widget for each button) # create a new window with a given title, and nice size dialog = gtk.Dialog() @@ -43,13 +43,13 @@ def __init__(self): # typically we quit if someone tries to close us dialog.connect("delete_event", self.delete_event) - # to make it nice we'll put the toolbar into the handle box, + # to make it nice we'll put the toolbar into the handle box, # so that it can be detached from the main window handlebox = gtk.HandleBox() dialog.vbox.pack_start(handlebox, False, False, 5) # toolbar will be horizontal, with both icons and text, and - # with 5pxl spaces between items and finally, + # with 5pxl spaces between items and finally, # we'll also put it into our handlebox toolbar = gtk.Toolbar() toolbar.set_orientation(gtk.ORIENTATION_HORIZONTAL) @@ -128,7 +128,7 @@ def __init__(self): toolbar.append_space() tooltips_button.set_active(True) - # to pack a widget into toolbar, we only have to + # to pack a widget into toolbar, we only have to # create it and append it with an appropriate tooltip entry = gtk.Entry() toolbar.append_widget(entry, "This is just an entry", "Private") diff --git a/pygtkweb/demos/035-notebook.py b/pygtkweb/demos/035-notebook.py index 97319084c..03506bed7 100644 --- a/pygtkweb/demos/035-notebook.py +++ b/pygtkweb/demos/035-notebook.py @@ -16,7 +16,7 @@ def tabsborder_book(self, button, notebook): tval = False bval = False if self.show_tabs == False: - tval = True + tval = True if self.show_border == False: bval = True @@ -29,7 +29,7 @@ def tabsborder_book(self, button, notebook): def remove_book(self, button, notebook): page = notebook.get_current_page() notebook.remove_page(page) - # Need to refresh the widget -- + # Need to refresh the widget -- # This forces the widget to redraw itself. notebook.queue_draw_area(0,0,-1,-1) @@ -69,7 +69,7 @@ def __init__(self): label = gtk.Label(bufferl) notebook.append_page(frame, label) - + # Now let's add a page to a specific spot checkbutton = gtk.CheckButton("Check me please!") checkbutton.set_size_request(100, 75) @@ -94,7 +94,7 @@ def __init__(self): label = gtk.Label(bufferl) notebook.prepend_page(frame, label) - + # Set what page to start at (page 4) notebook.set_current_page(3) diff --git a/pygtkweb/demos/038-menu.py b/pygtkweb/demos/038-menu.py index 3a71cc794..cd07555d1 100644 --- a/pygtkweb/demos/038-menu.py +++ b/pygtkweb/demos/038-menu.py @@ -15,7 +15,7 @@ def __init__(self): window.connect("delete_event", lambda w,e: gtk.main_quit()) # Init the menu-widget, and remember -- never - # show() the menu widget!! + # show() the menu widget!! # This is the menu that holds the menu items, the one that # will pop up when you click on the "Root Menu" in the app menu = gtk.Menu() diff --git a/pygtkweb/demos/039-itemfactory.py b/pygtkweb/demos/039-itemfactory.py index 55a2ece97..ca63162db 100644 --- a/pygtkweb/demos/039-itemfactory.py +++ b/pygtkweb/demos/039-itemfactory.py @@ -31,7 +31,7 @@ def print_hello(self, w, data): # <path> -> path of a radio item to link against # "<Separator>" -> create a separator # "<Branch>" -> create an item to hold sub items (optional) - # "<LastBranch>" -> create a right justified branch + # "<LastBranch>" -> create a right justified branch def get_main_menu(self, window): accel_group = gtk.AccelGroup() diff --git a/pygtkweb/demos/041-textview-basic.py b/pygtkweb/demos/041-textview-basic.py index 19f794a06..bdfbaea31 100644 --- a/pygtkweb/demos/041-textview-basic.py +++ b/pygtkweb/demos/041-textview-basic.py @@ -38,7 +38,7 @@ def close_application(self, widget): def __init__(self): window = gtk.Window(gtk.WINDOW_TOPLEVEL) - window.set_resizable(True) + window.set_resizable(True) window.connect("destroy", self.close_application) window.set_title("TextView Widget Basic Example") window.set_border_width(0) @@ -158,7 +158,7 @@ def __init__(self): def main(): gtk.main() - return 0 + return 0 if __name__ == "__main__": TextViewExample() diff --git a/pygtkweb/demos/042-testtext.py b/pygtkweb/demos/042-testtext.py index ed3212bae..8ab23730e 100644 --- a/pygtkweb/demos/042-testtext.py +++ b/pygtkweb/demos/042-testtext.py @@ -116,7 +116,7 @@ def __init__(self): for i in range(Buffer.N_COLORS): tag = self.create_tag() self.color_tags.append(tag) - + #self.invisible_tag = self.create_tag(None, invisible=True) self.not_editable_tag = self.create_tag(editable=False, foreground="purple") @@ -152,7 +152,7 @@ def search(self, str, view, forward): # remove tag from whole buffer start, end = self.get_bounds() self.remove_tag(self.found_text_tag, start, end) - + iter = self.get_iter_at_mark(self.get_insert()) i = 0 @@ -183,7 +183,7 @@ def search(self, str, view, forward): "%d strings found and marked in red" % i) dialog.connect("response", lambda x,y: dialog.destroy()) - + dialog.show() def search_forward(self, str, view): @@ -215,7 +215,7 @@ def set_colors(self, enabled): elif (not enabled and self.color_cycle_timeout_id != 0): gtk.timeout_remove(self.color_cycle_timeout_id) self.color_cycle_timeout_id = 0 - + for tag in self.color_tags: if enabled: color = apply(TestText.colormap.alloc_color, @@ -224,10 +224,10 @@ def set_colors(self, enabled): else: tag.set_property("foreground_set", False) hue += 1.0 / Buffer.N_COLORS - + def cycle_colors(self): hue = self.start_hue - + for tag in self.color_tags: color = apply(TestText.colormap.alloc_color, hue_to_color (hue)) @@ -315,7 +315,7 @@ def fill_example_buffer(self): for i in range(100): iter = self.get_iter_at_offset(0) self.insert_pixbuf(iter, pixbuf) - + str = "%d Hello World! blah blah blah blah blah blah blah blah blah blah blah blah\nwoo woo woo woo woo woo woo woo woo woo woo woo woo woo woo\n" % i self.insert(iter, str) @@ -337,11 +337,11 @@ def fill_example_buffer(self): iter = self.get_iter_at_line_offset(1, 14) iter2 = self.get_iter_at_line_offset(1, 24) self.apply_tag_by_name("strikethrough", iter, iter2) - + iter = self.get_iter_at_line_offset(0, 9) iter2 = self.get_iter_at_line_offset(0, 16) self.apply_tag_by_name("bg_green", iter, iter2) - + iter = self.get_iter_at_line_offset(4, 2) iter2 = self.get_iter_at_line_offset(4, 10) self.apply_tag_by_name("bg_green", iter, iter2) @@ -352,7 +352,7 @@ def fill_example_buffer(self): iter = self.get_iter_at_mark(temp_mark) self.insert(iter, "Centered text!\n") - + iter2 = self.get_iter_at_mark(temp_mark) self.apply_tag_by_name("centered", iter2, iter) @@ -365,7 +365,7 @@ def fill_example_buffer(self): self.insert_with_tags(iter, "Paragraph with negative indentation. blah blah blah blah blah. The quick brown fox jumped over the lazy dog.\n", self.get_tag_table().lookup("negative_indent")) - + print "%d lines %d chars\n" % (self.get_line_count(), self.get_char_count()) @@ -386,7 +386,7 @@ def fill_file_buffer(self, filename): result = dialog.run() dialog.destroy() return False - + iter = self.get_iter_at_offset(0) buf = f.read() f.close() @@ -446,7 +446,7 @@ def save_buffer(self): gtk.BUTTONS_OK, err); dialog.run() dialog.destroy() - + return result def save_as_ok_func(self, filename): @@ -463,7 +463,7 @@ def save_as_ok_func(self, filename): dialog.destroy() if result != gtk.RESPONSE_YES: return False - + self.filename = filename if self.save_buffer(): @@ -556,10 +556,10 @@ def __init__(self, buffer=None): TestText.views.push(self) buffer.ref() - + if not TestText.colormap: TestText.colormap = self.get_colormap() - + self.connect("delete_event", self.delete_event_cb) self.accel_group = gtk.AccelGroup() @@ -575,7 +575,7 @@ def __init__(self, buffer=None): vbox.pack_start(self.item_factory.get_widget("<main>"), False, False, 0) - + sw = gtk.ScrolledWindow() sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) @@ -585,7 +585,7 @@ def __init__(self, buffer=None): # Make sure border width works, no real reason to do this other # than testing self.text_view.set_border_width(10) - + # Draw tab stops in the top and bottom windows. self.text_view.set_border_window_size(gtk.TEXT_WINDOW_TOP, 15) self.text_view.set_border_window_size(gtk.TEXT_WINDOW_BOTTOM, 15) @@ -593,14 +593,14 @@ def __init__(self, buffer=None): self.text_view.connect("expose_event", self.tab_stops_expose) self.bhid = buffer.connect("mark_set", self.cursor_set_callback) - + # Draw line numbers in the side windows; we should really be # more scientific about what width we set them to. self.text_view.set_border_window_size(gtk.TEXT_WINDOW_RIGHT, 30) self.text_view.set_border_window_size(gtk.TEXT_WINDOW_LEFT, 30) self.text_view.connect("expose_event", self.line_numbers_expose) - + vbox.pack_start(sw, True, True, 0) sw.add(self.text_view) @@ -610,7 +610,7 @@ def __init__(self, buffer=None): self.set_view_title() self.init_menus() self.add_example_widgets() - + self.show_all() def delete_event_cb(self, window, event, data=None): @@ -802,7 +802,7 @@ def dialog_response_callback(self, dialog, response_id): response_id != RESPONSE_BACKWARD): dialog.destroy() return - + start, end = dialog.buffer.get_bounds() search_string = start.get_text(end) @@ -813,7 +813,7 @@ def dialog_response_callback(self, dialog, response_id): buffer.search_forward(search_string, self) elif response_id == RESPONSE_BACKWARD: buffer.search_backward(search_string, self) - + dialog.destroy() def do_search(self, callback_action, widget): @@ -841,7 +841,7 @@ def movable_child_callback(self, child, event): info['start_y'] = -1 info['button'] = -1 child.set_data("testtext-move-info", info) - + if event.type == gtk.gdk.BUTTON_PRESS: if info['button'] < 0: info['button'] = event.button @@ -875,8 +875,8 @@ def movable_child_callback(self, child, event): return False def add_movable_child(self, text_view, window): - label = gtk.Label("Drag me around") - + label = gtk.Label("Drag me around") + event_box = gtk.EventBox() event_box.add_events(gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK | @@ -903,7 +903,7 @@ def do_add_children(self, callback_action, widget): def do_add_focus_children(self, callback_action, widget): text_view = self.text_view - + child = gtk.EventBox() b = gtk.Button("Button _A in widget.window") child.add(b) @@ -1002,13 +1002,13 @@ def set_view_title(self): def cursor_set_callback(self, buffer, location, mark): # Redraw tab windows if the cursor moves # on the mapped widget (windows may not exist before realization... - + text_view = self.text_view if mark == buffer.get_insert(): tab_window = text_view.get_window(gtk.TEXT_WINDOW_TOP) tab_window.invalidate_rect(None, False) #tab_window.invalidate_rect(tab_window.get_geometry()[:4], False) - + tab_window = text_view.get_window(gtk.TEXT_WINDOW_BOTTOM) tab_window.invalidate_rect(None, False) #tab_window.invalidate_rect(tab_window.get_geometry()[:4], False) @@ -1016,7 +1016,7 @@ def cursor_set_callback(self, buffer, location, mark): def tab_stops_expose(self, widget, event): #print self, widget, event text_view = widget - + # See if this expose is on the tab stop window top_win = text_view.get_window(gtk.TEXT_WINDOW_TOP) bottom_win = text_view.get_window(gtk.TEXT_WINDOW_BOTTOM) @@ -1046,11 +1046,11 @@ def tab_stops_expose(self, widget, event): if attrs.tabs: tabslist = attrs.tabs.get_tabs() in_pixels = attrs.tabs.get_positions_in_pixels() - + for align, position in tabslist: if not in_pixels: position = pango.PIXELS(position) - + pos, y = text_view.buffer_to_window_coords(type, position, 0) target.draw_line(text_view.style.fg_gc[text_view.state], pos, 0, pos, 15) @@ -1081,7 +1081,7 @@ def get_lines(self, first_y, last_y, buffer_coords, numbers): def line_numbers_expose(self, widget, event, user_data=None): text_view = widget - + # See if this expose is on the line numbers window left_win = text_view.get_window(gtk.TEXT_WINDOW_LEFT) right_win = text_view.get_window(gtk.TEXT_WINDOW_RIGHT) @@ -1094,7 +1094,7 @@ def line_numbers_expose(self, widget, event, user_data=None): target = right_win else: return False - + first_y = event.area.y last_y = first_y + event.area.height @@ -1104,10 +1104,10 @@ def line_numbers_expose(self, widget, event, user_data=None): numbers = [] pixels = [] count = self.get_lines(first_y, last_y, pixels, numbers) - + # Draw fully internationalized numbers! layout = widget.create_pango_layout("") - + for i in range(count): x, pos = text_view.buffer_to_window_coords(type, 0, pixels[i]) str = "%d" % numbers[i] @@ -1120,7 +1120,7 @@ def line_numbers_expose(self, widget, event, user_data=None): def add_example_widgets(self): buffer = self.text_view.get_buffer() - + anchor = buffer.get_data("anchor") if (anchor and not anchor.get_deleted()): @@ -1140,7 +1140,7 @@ def pop(self): def get(self): return self[0] - + class TestText: untitled_serial = 1 colormap = None diff --git a/pygtkweb/demos/045-filelisting.py b/pygtkweb/demos/045-filelisting.py index 3f1cfe846..80404b793 100644 --- a/pygtkweb/demos/045-filelisting.py +++ b/pygtkweb/demos/045-filelisting.py @@ -59,23 +59,23 @@ class FileListingCellDataExample: def delete_event(self, widget, event, data=None): gtk.main_quit() return False - + def __init__(self, dname = None): cell_data_funcs = (None, self.file_size, self.file_mode, self.file_last_changed) - + # Create a new window self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) - + self.window.set_size_request(400, 300) - + self.window.connect("delete_event", self.delete_event) - + listmodel = self.make_list(dname) - + # create the TreeView self.treeview = gtk.TreeView() - + # create the TreeViewColumns to display the data self.tvcolumn = [None] * len(self.column_names) cellpb = gtk.CellRendererPixbuf() @@ -98,7 +98,7 @@ def __init__(self, dname = None): self.scrolledwindow.add(self.treeview) self.window.add(self.scrolledwindow) self.treeview.set_model(listmodel) - + self.window.show_all() return diff --git a/pygtkweb/demos/046-cellrenderer.py b/pygtkweb/demos/046-cellrenderer.py index 686b87bbd..3e9e0956c 100644 --- a/pygtkweb/demos/046-cellrenderer.py +++ b/pygtkweb/demos/046-cellrenderer.py @@ -10,7 +10,7 @@ "Do some programming": "Remember to update your software", "Power up systems": "Turn on the client but leave the server", "Watch some tv": "Remember to catch ER" - } + } class GUI_Controller: """ The GUI class is the controller for our application """ @@ -50,7 +50,7 @@ def __init__(self): def get_model(self): """ Returns the model """ if self.tree_store: - return self.tree_store + return self.tree_store else: return None @@ -70,12 +70,12 @@ def make_view( self, model ): self.renderer1 = gtk.CellRendererToggle() self.renderer1.set_property('activatable', True) self.renderer1.connect( 'toggled', self.col1_toggled_cb, model ) - + # Connect column0 of the display with column 0 in our list model # The renderer will then display whatever is in column 0 of # our model . self.column0 = gtk.TreeViewColumn("Name", self.renderer, text=0) - + # The columns active state is attached to the second column # in the model. So when the model says True then the button # will show as active e.g on. @@ -101,7 +101,7 @@ def col1_toggled_cb( self, cell, path, model ): return if __name__ == '__main__': - Store = InfoModel() + Store = InfoModel() Display = DisplayModel() myGUI = GUI_Controller() myGUI.run() diff --git a/pygtkweb/demos/048-treemodelsort.py b/pygtkweb/demos/048-treemodelsort.py index dfb13a651..7393fecfe 100644 --- a/pygtkweb/demos/048-treemodelsort.py +++ b/pygtkweb/demos/048-treemodelsort.py @@ -35,7 +35,7 @@ def __init__(self): # Create new windows self.w = [None] * 3 - + for n in range(3): self.w[n] = gtk.Window(gtk.WINDOW_TOPLEVEL) win = self.w[n] diff --git a/pygtkweb/demos/049-filelisting-gtm.py b/pygtkweb/demos/049-filelisting-gtm.py index cdd0de49a..9b48756a2 100644 --- a/pygtkweb/demos/049-filelisting-gtm.py +++ b/pygtkweb/demos/049-filelisting-gtm.py @@ -153,20 +153,20 @@ class GenericTreeModelExample: def delete_event(self, widget, event, data=None): gtk.main_quit() return False - + def __init__(self): # Create a new window self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) - + self.window.set_size_request(300, 200) - + self.window.connect("delete_event", self.delete_event) - + self.listmodel = FileListModel() - + # create the TreeView self.treeview = gtk.TreeView() - + # create the TreeViewColumns to display the data column_names = self.listmodel.get_column_names() self.tvcolumn = [None] * len(column_names) @@ -201,7 +201,7 @@ def open_file(self, treeview, path, column): self.window.set_title(new_model.dirname) treeview.set_model(new_model) return - + def main(): gtk.main() diff --git a/pygtkweb/demos/062-uimanager.py b/pygtkweb/demos/062-uimanager.py index 247346699..0b41ac629 100644 --- a/pygtkweb/demos/062-uimanager.py +++ b/pygtkweb/demos/062-uimanager.py @@ -31,7 +31,7 @@ class UIManagerExample: </placeholder> </toolbar> </ui>''' - + def __init__(self): # Create the toplevel window window = gtk.Window() diff --git a/pygtkweb/demos/063-uimerge.py b/pygtkweb/demos/063-uimerge.py index 79758bbbb..317032151 100644 --- a/pygtkweb/demos/063-uimerge.py +++ b/pygtkweb/demos/063-uimerge.py @@ -31,7 +31,7 @@ class UIMergeExample: </placeholder> </toolbar> </ui>''' - + ui1 = '''<ui> <menubar name="MenuBar"> <menu action="File"> @@ -58,7 +58,7 @@ class UIMergeExample: </placeholder> </toolbar> </ui>''' - + def __init__(self): # Create the toplevel window window = gtk.Window() diff --git a/pygtkweb/demos/064-getselection.py b/pygtkweb/demos/064-getselection.py index e1aeaa260..0b0eb7b4b 100644 --- a/pygtkweb/demos/064-getselection.py +++ b/pygtkweb/demos/064-getselection.py @@ -40,7 +40,7 @@ def selection_received(self, widget, selection_data, data): print "Selection was not returned as \"STRING\" or \"ATOM\"!" return False - + def __init__(self): # Create the toplevel window diff --git a/pygtkweb/demos/065-setselection.py b/pygtkweb/demos/065-setselection.py index 351c19012..7723d2636 100644 --- a/pygtkweb/demos/065-setselection.py +++ b/pygtkweb/demos/065-setselection.py @@ -52,7 +52,7 @@ def __init__(self): eventbox = gtk.EventBox() eventbox.show() window.add(eventbox) - + # Create a toggle button to act as the selection selection_button = gtk.ToggleButton("Claim Selection") eventbox.add(selection_button) diff --git a/pygtkweb/demos/067-dragndrop.py b/pygtkweb/demos/067-dragndrop.py index 8bfdc257c..b58edf0aa 100644 --- a/pygtkweb/demos/067-dragndrop.py +++ b/pygtkweb/demos/067-dragndrop.py @@ -50,7 +50,7 @@ def makeLayout(self): hScrollbar.show() table.attach(hScrollbar, 0, 1, 1, 2, gtk.FILL|gtk.SHRINK, gtk.FILL|gtk.SHRINK, - 0, 0) + 0, 0) # tell the scrollbars to use the layout widget's adjustments vAdjust = layout.get_vadjustment() vScrollbar.set_adjustment(vAdjust) diff --git a/pygtkweb/demos/068-scribblesimple.py b/pygtkweb/demos/068-scribblesimple.py index 61a420586..e7710db71 100644 --- a/pygtkweb/demos/068-scribblesimple.py +++ b/pygtkweb/demos/068-scribblesimple.py @@ -66,10 +66,10 @@ def motion_notify_event(widget, event): x = event.x y = event.y state = event.state - + if state & gtk.gdk.BUTTON1_MASK and pixmap is not None: draw_brush(widget, x, y) - + return True def main(): diff --git a/pygtkweb/demos/checkbutton.py b/pygtkweb/demos/checkbutton.py index f5782f8e7..2be729a19 100644 --- a/pygtkweb/demos/checkbutton.py +++ b/pygtkweb/demos/checkbutton.py @@ -78,7 +78,7 @@ def __init__(self): def main(): gtk.main() - return 0 + return 0 if __name__ == "__main__": CheckButton() diff --git a/pygtkweb/demos/helloworld.py b/pygtkweb/demos/helloworld.py index 4e691464a..3b4f9803b 100644 --- a/pygtkweb/demos/helloworld.py +++ b/pygtkweb/demos/helloworld.py @@ -32,41 +32,41 @@ def destroy(self, widget, data=None): def __init__(self): # create a new window self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) - + # When the window is given the "delete_event" signal (this is given # by the window manager, usually by the "close" option, or on the # titlebar), we ask it to call the delete_event () function # as defined above. The data passed to the callback # function is NULL and is ignored in the callback function. self.window.connect("delete_event", self.delete_event) - - # Here we connect the "destroy" event to a signal handler. + + # Here we connect the "destroy" event to a signal handler. # This event occurs when we call gtk_widget_destroy() on the window, # or if we return FALSE in the "delete_event" callback. self.window.connect("destroy", self.destroy) - + # Sets the border width of the window. self.window.set_border_width(10) - + # Creates a new button with the label "Hello World". self.button = gtk.Button("Hello World") - + # When the button receives the "clicked" signal, it will call the # function hello() passing it None as its argument. The hello() # function is defined above. self.button.connect("clicked", self.hello, None) - + # This will cause the window to be destroyed by calling # gtk_widget_destroy(window) when "clicked". Again, the destroy # signal could come from here, or the window manager. self.button.connect_object("clicked", gtk.Widget.destroy, self.window) - + # This packs the button into the window (a GTK container). self.window.add(self.button) - + # The final step is to display this newly created widget. self.button.show() - + # and the window self.window.show() diff --git a/pygtkweb/demos/rangewidgets.py b/pygtkweb/demos/rangewidgets.py index 2a597760c..1fdb75d73 100644 --- a/pygtkweb/demos/rangewidgets.py +++ b/pygtkweb/demos/rangewidgets.py @@ -49,7 +49,7 @@ def cb_draw_value(self, button): # Turn the value display on the scale widgets off or on depending # on the state of the checkbutton self.hscale.set_draw_value(button.get_active()) - self.vscale.set_draw_value(button.get_active()) + self.vscale.set_draw_value(button.get_active()) # makes the sample window @@ -73,7 +73,7 @@ def __init__(self): # scrollbar widgets, and the highest value you'll get is actually # (upper - page_size). adj1 = gtk.Adjustment(0.0, 0.0, 101.0, 0.1, 1.0, 1.0) - + self.vscale = gtk.VScale(adj1) scale_set_default_values(self.vscale) box2.pack_start(self.vscale, True, True, 0) @@ -109,7 +109,7 @@ def __init__(self): button.connect("toggled", self.cb_draw_value) box2.pack_start(button, True, True, 0) button.show() - + box2 = gtk.HBox(False, 10) box2.set_border_width(10) @@ -117,23 +117,23 @@ def __init__(self): label = gtk.Label("Scale Value Position:") box2.pack_start(label, False, False, 0) label.show() - + opt = gtk.OptionMenu() menu = gtk.Menu() item = make_menu_item ("Top", self.cb_pos_menu_select, gtk.POS_TOP) menu.append(item) - + item = make_menu_item ("Bottom", self.cb_pos_menu_select, gtk.POS_BOTTOM) menu.append(item) - + item = make_menu_item ("Left", self.cb_pos_menu_select, gtk.POS_LEFT) menu.append(item) - + item = make_menu_item ("Right", self.cb_pos_menu_select, gtk.POS_RIGHT) menu.append(item) - + opt.set_menu(menu) box2.pack_start(opt, True, True, 0) opt.show() @@ -149,32 +149,32 @@ def __init__(self): label = gtk.Label("Scale Update Policy:") box2.pack_start(label, False, False, 0) label.show() - + opt = gtk.OptionMenu() menu = gtk.Menu() - + item = make_menu_item("Continuous", self.cb_update_menu_select, gtk.UPDATE_CONTINUOUS) menu.append(item) - + item = make_menu_item ("Discontinuous", self.cb_update_menu_select, gtk.UPDATE_DISCONTINUOUS) menu.append(item) - + item = make_menu_item ("Delayed", self.cb_update_menu_select, gtk.UPDATE_DELAYED) menu.append(item) - + opt.set_menu(menu) box2.pack_start(opt, True, True, 0) opt.show() - + box1.pack_start(box2, True, True, 0) box2.show() box2 = gtk.HBox(False, 10) box2.set_border_width(10) - + # An HScale widget for adjusting the number of digits on the # sample scales. label = gtk.Label("Scale Digits:") @@ -190,10 +190,10 @@ def __init__(self): box1.pack_start(box2, True, True, 0) box2.show() - + box2 = gtk.HBox(False, 10) box2.set_border_width(10) - + # And, one last HScale widget for adjusting the page size of the # scrollbar. label = gtk.Label("Scrollbar Page Size:") @@ -229,7 +229,7 @@ def __init__(self): def main(): gtk.main() - return 0 + return 0 if __name__ == "__main__": RangeWidgets() diff --git a/pygtkweb/demos/table.py b/pygtkweb/demos/table.py index a69f53932..d1a48e2fc 100644 --- a/pygtkweb/demos/table.py +++ b/pygtkweb/demos/table.py @@ -79,7 +79,7 @@ def __init__(self): def main(): gtk.main() - return 0 + return 0 if __name__ == "__main__": t = Table() diff --git a/pygtkweb/library/browser.py b/pygtkweb/library/browser.py index 8a0ffd529..3b9f586f2 100644 --- a/pygtkweb/library/browser.py +++ b/pygtkweb/library/browser.py @@ -24,7 +24,7 @@ def __init__(self, tag=None, element=None): self.element = element else: raise Exception("Cannot create Element without tag or element") - + self.element.__ref = self; self.activeEvents = [] @@ -151,7 +151,7 @@ class Document: @staticmethod def createElement(tag): return Element(tag) - + @staticmethod def append(element): JS(''' diff --git a/pygtkweb/library/platform/browserhulahop.py b/pygtkweb/library/platform/browserhulahop.py index c4e653e48..4655deb57 100644 --- a/pygtkweb/library/platform/browserhulahop.py +++ b/pygtkweb/library/platform/browserhulahop.py @@ -38,7 +38,7 @@ def __init__(self, tag=None, element=None): self.element = element else: raise Exception("Cannot create Element without tag or element") - + self.activeEvents = [] def append(self, element): @@ -137,7 +137,7 @@ class Document: @staticmethod def createElement(tag): return Element(tag) - + @staticmethod def append(element): doc().body.appendChild(element.element) diff --git a/pyjd/hula.py b/pyjd/hula.py index 4e9a994cf..aadce3f0e 100644 --- a/pyjd/hula.py +++ b/pyjd/hula.py @@ -22,7 +22,7 @@ import sys import hulahop # this is for storing the gecko stuff (cache, cookies, plugins etc.) -gecko_path = os.environ.get('HOME', '.') +gecko_path = os.environ.get('HOME', '.') gecko_path = os.path.join(gecko_path, ".pyjd") hulahop.startup(gecko_path) @@ -125,16 +125,16 @@ def load_app(self): def do_setup(self): WebView.do_setup(self) self.progress.setup(self) - + def _addXMLHttpRequestEventListener(self, node, event_name, event_fn): - + listener = xpcom.server.WrapObject(ContentInvoker(node, event_fn), interfaces.nsIDOMEventListener) node.addEventListener(event_name, listener, False) return listener def addEventListener(self, node, event_name, event_fn): - + listener = xpcom.server.WrapObject(ContentInvoker(node, event_fn), interfaces.nsIDOMEventListener) node.addEventListener(event_name, listener, True) @@ -144,7 +144,7 @@ def mash_attrib(self, attrib_name): return attrib_name def _addWindowEventListener(self, event_name, event_fn, win=None): - + if win is None: win = self.window_root listener = xpcom.server.WrapObject(ContentInvoker(win, event_fn), @@ -156,12 +156,12 @@ def getDOMParser(self): xml_svc_cls = components.classes[ \ "@mozilla.org/xmlextras/domparser;1"] return xml_svc_cls.createInstance(interfaces.nsIDOMParser) - + def getXmlHttpRequest(self): xml_svc_cls = components.classes[ \ "@mozilla.org/xmlextras/xmlhttprequest;1"] return xml_svc_cls.createInstance(interfaces.nsIXMLHttpRequest) - + def getUri(self): return self.application diff --git a/pyjd/idlparser.py b/pyjd/idlparser.py index 59a196ec5..d8e69e076 100644 --- a/pyjd/idlparser.py +++ b/pyjd/idlparser.py @@ -208,7 +208,7 @@ def parse(self): self.parse_interface(l) elif l.startswith('coclass'): self.parse_coclass(l) - + if __name__ == '__main__': p = IdlParser(sys.argv[1]) diff --git a/pyjd/importers.py b/pyjd/importers.py index cd2b6ac17..03fd38070 100644 --- a/pyjd/importers.py +++ b/pyjd/importers.py @@ -134,7 +134,7 @@ def _fs_import(dir, modname, fqname): code = Module(mod, filename) code.compile() code = code.getCode() - + if platform_file and t_p_py: out_t_py = t_p_py out_filename = platform_file diff --git a/pyjd/mshtml.py b/pyjd/mshtml.py index 987e59fcf..d28e3f7f7 100644 --- a/pyjd/mshtml.py +++ b/pyjd/mshtml.py @@ -49,8 +49,8 @@ GetModule('msxml6.dll') except: pass - GetModule('mshtml.tlb') - #GetModule('progdlg.tlb') + GetModule('mshtml.tlb') + #GetModule('progdlg.tlb') from comtypes.gen import SHDocVw from comtypes.gen import MSHTML @@ -70,7 +70,7 @@ atl = windll.atl # If this fails, you need atl.dll # do this after gen stuff, above -import mshtmlevents +import mshtmlevents SID_SShellBrowser = GUID("{000214E2-0000-0000-C000-000000000046}") @@ -100,7 +100,7 @@ class IOleInPlaceActiveObject(IOleWindow): COMMETHOD([], HRESULT, 'TranslateAccelerator', ( ['in'], POINTER(MSG), 'pMsg' )) ] - + # http://www.mail-archive.com/comtypes-users@lists.sourceforge.net/msg00439.html class IServiceProvider(IUnknown): @@ -155,7 +155,7 @@ def DocumentComplete(self, this, *args): # in order to get at the URI. self.workaround_ignore_first_doc_complete = True return - + self._loaded() def NewWindow2(self, this, *args): @@ -242,7 +242,7 @@ def __init__(self, application, appdir): "AtlAxWin", "about:blank", WS_OVERLAPPEDWINDOW | - WS_VISIBLE | + WS_VISIBLE | WS_HSCROLL | WS_VSCROLL, CW_USEDEFAULT, CW_USEDEFAULT, @@ -313,7 +313,7 @@ def getDomWindow(self): return self.getDomDocument().parentWindow def _addXMLHttpRequestEventListener(self, node, event_name, event_fn): - + #print "_addXMLHttpRequestEventListener", event_name rcvr = mshtmlevents._DispEventReceiver() @@ -330,7 +330,7 @@ def _addXMLHttpRequestEventListener(self, node, event_name, event_fn): return ifc def addEventListener(self, node, event_name, event_fn): - + rcvr = mshtmlevents._DispEventReceiver() rcvr.dispmap = {0: event_fn} @@ -350,7 +350,7 @@ def mash_attrib(self, attrib_name): return attrib_name def _addWindowEventListener(self, event_name, event_fn, wnd=None): - + #print "_addWindowEventListener", event_name, event_fn #rcvr = mshtmlevents.GetDispEventReceiver(MSHTML.HTMLWindowEvents, # event_fn, "on%s" % event_name) @@ -379,11 +379,11 @@ def getXmlHttpRequest(self): o = comtypes.client.CreateObject('MSXML2.XMLHTTP.3.0') #print "getXMLHttpRequest", o return Dispatch(o) - + def getDOMParser(self): o = comtypes.client.CreateObject('MSXML.DOMDocument') return Dispatch(o) - + def getUri(self): return self.application @@ -410,7 +410,7 @@ def _loaded(self): if self.appdir: pth = os.path.abspath(self.appdir) sys.path.append(pth) - + def on_unload_callback(self, *args): PostQuitMessage(0) @@ -427,13 +427,13 @@ def MainWin(one_event): # Pump Messages msg = MSG() pMsg = pointer(msg) - + while 1: res = GetMessage( pMsg, NULL, 0, 0) if res == -1: return 0 if res == 0: - break + break if timer_q: fn = timer_q.pop() @@ -445,10 +445,10 @@ def MainWin(one_event): app = wv.pBrowser.Application ao = app.QueryInterface(IOleInPlaceActiveObject) if ao.TranslateAccelerator(pMsg): - #if not TranslateAccelerator( - # wv.hwnd, #handle to receiving window - # NULL, #handle to active accelerator table - # pMsg): #message data + #if not TranslateAccelerator( + # wv.hwnd, #handle to receiving window + # NULL, #handle to active accelerator table + # pMsg): #message data TranslateMessage(pMsg) DispatchMessage(pMsg) @@ -456,7 +456,7 @@ def MainWin(one_event): break return msg.wParam - + def add_timer_queue(fn): timer_q.append(fn) PostMessage(c_int(wv.hwnd), UINT(WM_USER_TIMER), WPARAM(0), LPARAM(0xffff)) diff --git a/pyjd/mshtmlevents.py b/pyjd/mshtmlevents.py index 28e49bbfb..ded891ff6 100644 --- a/pyjd/mshtmlevents.py +++ b/pyjd/mshtmlevents.py @@ -187,7 +187,7 @@ def PumpEvents(timeout): # If the calling thread resides in a multithread apartment (MTA), # CoWaitForMultipleHandles calls the Win32 function # MsgWaitForMultipleObjects. - + hevt = ctypes.windll.kernel32.CreateEventA(None, True, False, None) handles = (ctypes.c_void_p * 1)(hevt) RPC_S_CALLPENDING = -2147417835 @@ -232,7 +232,7 @@ def IDispatch_Invoke(self, this, memid, riid, lcid, wFlags, pDispParams, if mth is None: return S_OK dp = pDispParams[0] - #print "num args", dp.cArgs + #print "num args", dp.cArgs # DISPPARAMS contains the arguments in reverse order args = [dp.rgvarg[i].value for i in range(dp.cArgs)] #print "Event", self, memid, mth, args @@ -276,7 +276,7 @@ def _get_dispmap(interface): ## for info in interface._methods_: ## mth = getattr(interface, info.name) ## memid = mth.im_func.memid - + # See also MSDN docs for the 'defaultvtable' idl flag, or # IMPLTYPEFLAG_DEFAULTVTABLE. This is not a flag of the # interface, but of the coclass! diff --git a/pyjd/progresslistener.py b/pyjd/progresslistener.py index 459e8fc4d..15b991afd 100644 --- a/pyjd/progresslistener.py +++ b/pyjd/progresslistener.py @@ -51,21 +51,21 @@ def setup(self, browser): interfaces.nsIWebProgress.NOTIFY_LOCATION browser.web_progress.addProgressListener(self._wrapped_self, mask) - + def _reset_requests_count(self): self.total_requests = 0 self.completed_requests = 0 - + def onLocationChange(self, webProgress, request, location): self.emit('location-changed', location) - + def onProgressChange(self, webProgress, request, curSelfProgress, maxSelfProgress, curTotalProgress, maxTotalProgress): pass - + def onSecurityChange(self, webProgress, request, state): pass - + def onStateChange(self, webProgress, request, stateFlags, status): if stateFlags & interfaces.nsIWebProgressListener.STATE_IS_REQUEST: if stateFlags & interfaces.nsIWebProgressListener.STATE_START: @@ -76,7 +76,7 @@ def onStateChange(self, webProgress, request, stateFlags, status): if stateFlags & interfaces.nsIWebProgressListener.STATE_IS_NETWORK: if stateFlags & interfaces.nsIWebProgressListener.STATE_START: self.emit('loading-start') - self._reset_requests_count() + self._reset_requests_count() elif stateFlags & interfaces.nsIWebProgressListener.STATE_STOP: self.emit('loading-stop') diff --git a/pyjd/pyobjc.py b/pyjd/pyobjc.py index e1efb3d66..904d0dc7b 100644 --- a/pyjd/pyobjc.py +++ b/pyjd/pyobjc.py @@ -19,7 +19,7 @@ def loadURL_(self, sender): url = NSURL.URLWithString_(urlString) request = NSURLRequest.requestWithURL_(url) self.webview.mainFrame().loadRequest_(request) - + if __name__ == "__main__": AppHelper.runEventLoop() diff --git a/pyjd/pyqt4.py b/pyjd/pyqt4.py index 8c712df01..52084eea1 100644 --- a/pyjd/pyqt4.py +++ b/pyjd/pyqt4.py @@ -63,7 +63,7 @@ def item(self, idx): class _ElementBase(object): - + @property def nodeType(self): return self._js("nodeType") @@ -71,35 +71,35 @@ def nodeType(self): @property def innerHTML(self): return self.getAttribute("html") - + @property def length(self): return self.getAttribute("length") - + @property def type(self): return self.getAttribute("type") - + @property def offsetParent(self): return int(self.getAttribute("offsetParent") or "0") - + @property def offsetTop(self): return int(self.getAttribute("offsetTop") or "0") - + @property def offsetLeft(self): return int(self.getAttribute("offsetLeft") or "0") - + @property def scrollTop(self): return int(self.getAttribute("scrollTop") or "0") - + @property def firstChild(self): return int(self.getAttribute("firstChild") or None) @@ -112,7 +112,7 @@ def scrollLeft(self): @property def rows(self): return _RowElementProxy(self) - + def setInnerText(self, text): self.setInnerHTML(html_quote(text)) @@ -129,29 +129,29 @@ def insertChild(self, child, before_index): element.appendInside(child._element) - + def getParent(self): return _ElementProxy(self._element.parent()) - - + + def _js(self, cmd): return self._element.evaluateJavaScript("this.%s" % cmd) - - + + def cloneNode(self, arg): return _ElementProxy(self._element.clone()) def blur(self): self._js("blur()"); - + def focus(self): self._js("focus()"); class _NewElement(_ElementBase): - - + + def __init__(self, tag_name, **attrs): self._tag_name = tag_name.lower() self._inner_html = "" @@ -167,16 +167,16 @@ def setAttribute(self, name, value): if name.lower() == "style": print "Warning: style should be set with setStyleAttribute and not with setAttribute" self._attrs[name.lower()] = value - + def setStyleAttribute(self, name, value): self._styles[name.lower()] = value - - + + def setInnerHTML(self, html): self._inner_html = html - + def setInnerText(self, text): self._inner_html = html_quote(text) @@ -203,11 +203,11 @@ class _ElementProxy(_ElementBase): def __init__(self, element): self._element = element - + def __hash__(self): return hash(self._element) - + def __repr__(self): return "<%s>" % unicode(self._element.tagName()) @@ -218,7 +218,7 @@ def getAttribute(self, name, default=""): return _ElementProxy(value) return unicode(value) - + def setAttribute(self, name, value): if name == "className": name = "class" @@ -281,7 +281,7 @@ def JS(code): print "js: %r" % code global app print app.getDomDocument().evaluateJavaScript(code) - + @@ -353,18 +353,18 @@ def run(): print "-"*60 print _current_web_frame().toHtml() - - - + + + class Listener(QObject): - + def __init__(self, element, event, callback): QObject.__init__(self) self._element = element self._event = event self._callback = callback - + @pyqtSignature("QVariant", result="bool") def execute(self, event_data): class _Event(unicode): @@ -379,5 +379,5 @@ class _Event(unicode): return True return result - + diff --git a/pyjd/sessionhistory.py b/pyjd/sessionhistory.py index b50bb453d..50166cbb9 100644 --- a/pyjd/sessionhistory.py +++ b/pyjd/sessionhistory.py @@ -24,7 +24,7 @@ class HistoryListener(gobject.GObject): _com_interfaces_ = interfaces.nsISHistoryListener __gsignals__ = { - 'session-history-changed': (gobject.SIGNAL_RUN_FIRST, + 'session-history-changed': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ([int])), 'session-link-changed': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, diff --git a/pyjd/windows.py b/pyjd/windows.py index 3e4a6f657..eb8a6fe61 100644 --- a/pyjd/windows.py +++ b/pyjd/windows.py @@ -130,7 +130,7 @@ class ACCEL(Structure): _fields_ = [("fVirt", BYTE), ("key", WORD), ("cmd", WORD)] - + class CREATESTRUCT(Structure): _fields_ = [("lpCreateParams", LPVOID), ("hInstance", HINSTANCE), @@ -160,18 +160,18 @@ class PAINTSTRUCT(Structure): ("fIncUpdate", BOOL), ("rgbReserved", c_char * 32)] - + class MENUITEMINFO(Structure): _fields_ = [("cbSize", UINT), ("fMask", UINT), ("fType", UINT), - ("fState", UINT), + ("fState", UINT), ("wID", UINT), ("hSubMenu", HMENU), ("hbmpChecked", HBITMAP), ("hbmpUnchecked", HBITMAP), ("dwItemData", ULONG_PTR), - ("dwTypeData", LPTSTR), + ("dwTypeData", LPTSTR), ("cch", UINT), ("hbmpItem", HBITMAP)] @@ -320,7 +320,7 @@ def HIWORD(dword): MF_UNCHECKED= 0 MF_HILITE = 128 MF_UNHILITE = 0 - + RB_SETBARINFO = WM_USER + 4 RB_GETBANDCOUNT = WM_USER + 12 @@ -469,7 +469,7 @@ def GET_XY_LPARAM(lParam): if x > 32768: x = x - 65536 y = HIWORD(lParam) - return x, y + return x, y def GET_POINT_LPARAM(lParam): x, y = GET_XY_LPARAM(lParam) diff --git a/pyjs/jsonrpc/__init__.py b/pyjs/jsonrpc/__init__.py index 62e758a73..9995c6ca0 100644 --- a/pyjs/jsonrpc/__init__.py +++ b/pyjs/jsonrpc/__init__.py @@ -1,7 +1,7 @@ import sys import traceback -# some dog's dinner random ways to get a json library from somewhere... +# some dog's dinner random ways to get a json library from somewhere... try: import json except ImportError, e: @@ -9,7 +9,7 @@ import gluon.contrib.simplejson as json except ImportError, e: import simplejson as json - + # this base class, use it to call self.process class JSONRPCServiceBase: @@ -52,11 +52,11 @@ def process(self, data): return self.error(msgid, 100, 'method "%s" does not exist' % method) def listmethods(self): - return self.methods.keys() + return self.methods.keys() def jsonremote(service): """Make JSONRPCService a decorator so that you can write : - + import JSONRPCService (note: this must derive from JSONRPCServiceBase!) chatservice = JSONRPCService() diff --git a/pyjs/jsonrpc/cgihandler/__init__.py b/pyjs/jsonrpc/cgihandler/__init__.py index 22e29ab76..abbd25c66 100644 --- a/pyjs/jsonrpc/cgihandler/__init__.py +++ b/pyjs/jsonrpc/cgihandler/__init__.py @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from pyjs.jsonrpc import JSONRPCServiceBase, jsonremote @@ -39,8 +39,8 @@ def write_data(data, cookies): response += cookies+"\n" response += "Content-Length: %d\n\n" % len(data) response += data - - #on windows all \n are converted to \r\n if stdout is a terminal and + + #on windows all \n are converted to \r\n if stdout is a terminal and # is not set to binary mode :( #this will then cause an incorrect Content-length. #I have only experienced this problem with apache on Win so far. diff --git a/pyjs/jsonrpc/cherrypy/jsonrpc.py b/pyjs/jsonrpc/cherrypy/jsonrpc.py index b090075d1..04352dd02 100644 --- a/pyjs/jsonrpc/cherrypy/jsonrpc.py +++ b/pyjs/jsonrpc/cherrypy/jsonrpc.py @@ -13,7 +13,7 @@ # # def __init__(self, defaultPage): # JSONRPCService.__init__(self, defaultPage) -# self.add_method(self.echo.__name__, self.echo) +# self.add_method(self.echo.__name__, self.echo) # # def echo(self, msg): # return msg diff --git a/pyjs/jsonrpc/django/jsonformprocessor.py b/pyjs/jsonrpc/django/jsonformprocessor.py index 64cdf2cfd..60115d025 100644 --- a/pyjs/jsonrpc/django/jsonformprocessor.py +++ b/pyjs/jsonrpc/django/jsonformprocessor.py @@ -36,15 +36,15 @@ def wrapped(*args, **kwargs): return f(request, **params[0]) return f(request, *params, **kwargs) return wrapped - + class JSONRPCService: def __init__(self, method_map={}): self.method_map = method_map - + def add_method(self, name, method): self.method_map[name] = method - + @wr def __call__(self, request, extra=None): #TODO: add support for jsonrpc tag @@ -79,7 +79,7 @@ def __call__(self, request, extra=None): # part of the app: # (r'^formsservice/$', 'djangoapp.views.processor'), -from django import forms +from django import forms def builderrors(form): d = {} diff --git a/pyjs/jsonrpc/django/jsonrpc.py b/pyjs/jsonrpc/django/jsonrpc.py index f3004d948..1741f62ad 100644 --- a/pyjs/jsonrpc/django/jsonrpc.py +++ b/pyjs/jsonrpc/django/jsonrpc.py @@ -13,7 +13,7 @@ from pyjs.jsonrpc import JSONRPCServiceBase, jsonremote class JSONRPCService(JSONRPCServiceBase): - + def __call__(self, request, extra=None): return self.process(request.raw_post_data) diff --git a/pyjs/jsonrpc/mongrel2/__init__.py b/pyjs/jsonrpc/mongrel2/__init__.py index 3eb2e2e43..b90814387 100644 --- a/pyjs/jsonrpc/mongrel2/__init__.py +++ b/pyjs/jsonrpc/mongrel2/__init__.py @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ from pyjs.jsonrpc import JSONRPCServiceBase, jsonremote diff --git a/pyjs/jsonrpc/mongrel2/example.py b/pyjs/jsonrpc/mongrel2/example.py index bcc8ed494..8adddd5f6 100644 --- a/pyjs/jsonrpc/mongrel2/example.py +++ b/pyjs/jsonrpc/mongrel2/example.py @@ -15,7 +15,7 @@ You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ #from pyjs.jsonrpc.mongrel2 import Mongrel2JSONRPCService, jsonremote @@ -37,4 +37,4 @@ def echo(request, data): while True: print "WAITING FOR REQUEST" mongservice() # handles one request - + diff --git a/pyjs/src/pyjs/browser.py b/pyjs/src/pyjs/browser.py index 3a07012b0..ad31872b4 100644 --- a/pyjs/src/pyjs/browser.py +++ b/pyjs/src/pyjs/browser.py @@ -325,7 +325,7 @@ def _create_app_html(self): html_output_filename = os.path.join(self.output, self.top_module + '.html') if self.apploader_file is None: - file_name = html_output_filename + file_name = html_output_filename else: file_name = self.apploader_file @@ -407,9 +407,9 @@ def build(top_module, pyjs, options, app_platforms, runtime_options, args): print "Building :", top_module print "PYJSPATH :", '\n '.join(['['] + [p for p in pyjs.path]) + '\n]' - + translator_arguments= translator.get_compile_options(options) - + l = BrowserLinker(args, output=options.output, platforms=app_platforms, diff --git a/pyjs/src/pyjs/builtin/pyjslib.py b/pyjs/src/pyjs/builtin/pyjslib.py index a296df0ee..6276b94f7 100644 --- a/pyjs/src/pyjs/builtin/pyjslib.py +++ b/pyjs/src/pyjs/builtin/pyjslib.py @@ -953,7 +953,7 @@ def ___import___(path, context, module_name=None, get_base=True): if get_base: return JS("$pyjs.loaded_modules[@{{topName}}]") return module - + # If we are here, the module is not loaded (yet). if JS("$pyjs.options.dynamic_loading"): module = __dynamic_load__(importName) @@ -4110,7 +4110,7 @@ def __getitem__(self, _index): def __len__(self): return INT(JS("""@{{self}}.__array.length""")) - + def index(self, value, _start=0): JS(""" var start = @{{_start}}.valueOf(); @@ -4134,7 +4134,7 @@ def index(self, value, _start=0): } } """) - raise ValueError("list.index(x): x not in list") + raise ValueError("list.index(x): x not in list") def __contains__(self, value): try: @@ -4602,7 +4602,7 @@ def __init__(self, a1, *args): self.stop = a1 self.start = None self.step = None - + def __cmp__(self, x): r = cmp(self.start, x.start) if r != 0: @@ -4611,8 +4611,8 @@ def __cmp__(self, x): if r != 0: return r r = cmp(self.step, x.step) - return r - + return r + def indices(self, length): """ PySlice_GetIndicesEx at ./Objects/sliceobject.c @@ -4626,14 +4626,14 @@ def indices(self, length): step = self.step if step == 0: raise ValueError("slice step cannot be zero") - + if step < 0: defstart = length - 1 defstop = -1 else: defstart = 0 defstop = length - + if self.start is None: start = defstart else: @@ -4650,7 +4650,7 @@ def indices(self, length): start = length - 1 else: start = length - + if self.stop is None: stop = defstop else: @@ -4675,11 +4675,11 @@ def indices(self, length): slicelength = (stop - start + 1)/step + 1; else: slicelength = (stop - start - 1)/step + 1; - + return (start, stop, step) def __repr__(self): - return "slice(%s, %s, %s)" % (self.start, self.stop, self.step) + return "slice(%s, %s, %s)" % (self.start, self.stop, self.step) JS("@{{slice}}.__str__ = @{{slice}}.__repr__;") JS("@{{slice}}.toString = @{{slice}}.__str__;") @@ -5703,7 +5703,7 @@ def xrange(start, stop = None, step = 1): @{{!x}}['__str__'] = @{{!x}}.toString; return @{{!x}}; """) - + def get_len_of_range(lo, hi, step): n = 0 JS(""" @@ -5723,10 +5723,10 @@ def range(start, stop = None, step = 1): raise TypeError("xrange() integer end argument expected, got %s" % stop.__class__.__name__) if not JS("@{{step}}!== null && @{{step}}.__number__ && (@{{step}}.__number__ != 0x01 || isFinite(@{{step}}))"): raise TypeError("xrange() integer step argument expected, got %s" % step.__class__.__name__) - + if step == 0: raise ValueError("range() step argument must not be zero") - + if step > 0: n = get_len_of_range(ilow, stop, step) else: @@ -6389,13 +6389,13 @@ class complex: def __init__(self, real, imag): self.real = float(real) self.imag = float(imag) - + def __repr__(self): if self.real: return "(%s+%sj)" % (self.real, self.imag) else: return "%sj" % self.imag - + def __add__(self, b): if isinstance(b, complex): return complex(self.real + b.real, self.imag + b.imag) @@ -6403,7 +6403,7 @@ def __add__(self, b): return complex(self.real + b, self.imag) else: raise TypeError("unsupported operand type(s) for +: '%r', '%r'" % (self, b)) - + JS("@{{complex}}['__radd__'] = @{{complex}}['__add__'];") JS("@{{complex}}['__str__'] = @{{complex}}['__repr__'];") JS("@{{complex}}['toString'] = @{{complex}}['__repr__'];") @@ -8266,7 +8266,7 @@ def __with(mgr, func): # The normal and non-local-goto cases are handled here if exc: exit(mgr, None, None, None) - + init() Ellipsis = EllipsisType() diff --git a/pyjs/src/pyjs/lib/base64.py b/pyjs/src/pyjs/lib/base64.py index f26456519..07e12bc05 100644 --- a/pyjs/src/pyjs/lib/base64.py +++ b/pyjs/src/pyjs/lib/base64.py @@ -46,7 +46,7 @@ def _translate(s, altchars): return t - + # Base64 encoding/decoding uses binascii def b64encode(s, altchars=None): @@ -122,7 +122,7 @@ def urlsafe_b64decode(s): return b64decode(s, '-_') - + # Base32 encoding/decoding must be done in Python _b32alphabet = { 0: 'A', 9: 'J', 18: 'S', 27: '3', @@ -262,7 +262,7 @@ def b32decode(s, casefold=False, map01=None): return EMPTYSTRING.join(parts) - + # RFC 3548, Base 16 Alphabet specifies uppercase, but hexlify() returns # lowercase. The RFC also recommends against accepting input case # insensitively. @@ -300,7 +300,7 @@ def b16decode(s, casefold=False): return binascii.unhexlify(s) - + # Legacy interface. This code could be cleaned up since I don't believe # binascii has any line length limitations. It just doesn't seem worth it # though. diff --git a/pyjs/src/pyjs/lib/binascii.py b/pyjs/src/pyjs/lib/binascii.py index d3a763056..52912905f 100644 --- a/pyjs/src/pyjs/lib/binascii.py +++ b/pyjs/src/pyjs/lib/binascii.py @@ -14,7 +14,7 @@ class Incomplete(Exception): def a2b_uu(s): if not s: return '' - + length = (ord(s[0]) - 0x20) % 64 def quadruplets_gen(s): @@ -54,7 +54,7 @@ def quadruplets_gen(s): result += ((length - len(result)) * '\x00') return result - + def b2a_uu(s): length = len(s) if length > 45: @@ -179,7 +179,7 @@ def next_valid_char(s, pos): if table_a2b_base64.has_key(c): return c return None - + quad_pos = 0 leftbits = 0 leftchar = 0 @@ -205,9 +205,9 @@ def next_valid_char(s, pos): leftchar &= ((1 << leftbits) - 1) if leftbits != 0: raise Error('Incorrect padding') - + return ''.join([chr(i) for i in res]) - + table_b2a_base64 = \ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" @@ -234,7 +234,7 @@ def triples_gen(s): return iterlist s = s[3:] return iterlist - + a = triples_gen(s[ :length - final_length]) result = [''.join( @@ -366,7 +366,7 @@ def b2a_qp(data, quotetabs=False, istext=True, header=False): def hex(n): if n == 0: return '0' - + if n < 0: n = -n sign = '-' @@ -391,7 +391,7 @@ def hex_gen(n): def two_hex_digits(n): return hex_numbers[n / 0x10] + hex_numbers[n % 0x10] - + def strhex_to_int(s): i = 0 @@ -404,39 +404,39 @@ def strhex_to_int(s): DONE = 0x7f SKIP = 0x7e FAIL = 0x7d - + table_a2b_hqx = [ - #^@ ^A ^B ^C ^D ^E ^F ^G + #^@ ^A ^B ^C ^D ^E ^F ^G FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - #\b \t \n ^K ^L \r ^N ^O + #\b \t \n ^K ^L \r ^N ^O FAIL, FAIL, SKIP, FAIL, FAIL, SKIP, FAIL, FAIL, - #^P ^Q ^R ^S ^T ^U ^V ^W + #^P ^Q ^R ^S ^T ^U ^V ^W FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - #^X ^Y ^Z ^[ ^\ ^] ^^ ^_ + #^X ^Y ^Z ^[ ^\ ^] ^^ ^_ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, - # ! " # $ % & ' + # ! " # $ % & ' FAIL, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, - #( ) * + , - . / + #( ) * + , - . / 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, FAIL, FAIL, - #0 1 2 3 4 5 6 7 + #0 1 2 3 4 5 6 7 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, FAIL, - #8 9 : ; < = > ? + #8 9 : ; < = > ? 0x14, 0x15, DONE, FAIL, FAIL, FAIL, FAIL, FAIL, - #@ A B C D E F G + #@ A B C D E F G 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, - #H I J K L M N O + #H I J K L M N O 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, FAIL, - #P Q R S T U V W + #P Q R S T U V W 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, FAIL, - #X Y Z [ \ ] ^ _ + #X Y Z [ \ ] ^ _ 0x2C, 0x2D, 0x2E, 0x2F, FAIL, FAIL, FAIL, FAIL, - #` a b c d e f g + #` a b c d e f g 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, FAIL, - #h i j k l m n o + #h i j k l m n o 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, FAIL, FAIL, - #p q r s t u v w + #p q r s t u v w 0x3D, 0x3E, 0x3F, FAIL, FAIL, FAIL, FAIL, FAIL, - #x y z { | } ~ ^? + #x y z { | } ~ ^? FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, @@ -493,7 +493,7 @@ def quadruples_gen(s): t = [] iterlist.append(t) return iterlist, False - + done = 0 try: #for snippet in quadruples_gen(s): @@ -501,14 +501,14 @@ def quadruples_gen(s): for snippet in iterlist: length = len(snippet) if length == 4: - result.append(chr(((snippet[0] & 0x3f) << 2) | (snippet[1] >> 4))) - result.append(chr(((snippet[1] & 0x0f) << 4) | (snippet[2] >> 2))) - result.append(chr(((snippet[2] & 0x03) << 6) | (snippet[3]))) + result.append(chr(((snippet[0] & 0x3f) << 2) | (snippet[1] >> 4))) + result.append(chr(((snippet[1] & 0x0f) << 4) | (snippet[2] >> 2))) + result.append(chr(((snippet[2] & 0x03) << 6) | (snippet[3]))) elif length == 3: - result.append(chr(((snippet[0] & 0x3f) << 2) | (snippet[1] >> 4))) - result.append(chr(((snippet[1] & 0x0f) << 4) | (snippet[2] >> 2))) + result.append(chr(((snippet[0] & 0x3f) << 2) | (snippet[1] >> 4))) + result.append(chr(((snippet[1] & 0x0f) << 4) | (snippet[2] >> 2))) elif length == 2: - result.append(chr(((snippet[0] & 0x3f) << 2) | (snippet[1] >> 4))) + result.append(chr(((snippet[0] & 0x3f) << 2) | (snippet[1] >> 4))) except Done: done = 1 except Error: @@ -621,7 +621,7 @@ def rlecode_hqx(s): s = s[1:] + '?' else: s = s[1:] + '!' - + for c in s: if c == prev and count < 255: count += 1 @@ -640,10 +640,10 @@ def rlecode_hqx(s): if prev != '\x90': result.extend([prev, '\x90', chr(count)]) else: - result.extend(['\x90', '\x00', '\x90', chr(count)]) + result.extend(['\x90', '\x00', '\x90', chr(count)]) count = 1 prev = c - + return ''.join(result) def rledecode_hqx(s): @@ -725,7 +725,7 @@ def crc32(s, crc=0): #/* Note: (crc >> 8) MUST zero fill on left result = crc ^ 0xffffffffL - + if result > 2**31: result = ((result + 2**31) % 2**32) - 2**31 @@ -790,6 +790,6 @@ def pairs_gen(s): raise TypeError('Non-hexadecimal digit found') result.append(chr((a << 4) + b)) return ''.join(result) - + unhexlify = a2b_hex diff --git a/pyjs/src/pyjs/lib/datetime.py b/pyjs/src/pyjs/lib/datetime.py index 814680f69..ca7b9b8ba 100644 --- a/pyjs/src/pyjs/lib/datetime.py +++ b/pyjs/src/pyjs/lib/datetime.py @@ -17,26 +17,26 @@ def __init__(self, year, month, day, d=None): self.year = d.getFullYear() self.month = d.getMonth() + 1.0 self.day = d.getDate() - + @classmethod def today(self): return date(d=JS("""new Date()""")) - + @classmethod def fromtimestamp(self, timestamp): d = JS("""new Date()""") d.setTime(timestamp * 1000.0) return date(0, 0, 0, d=d) - + @classmethod def fromordinal(self, ordinal): t = __Jan_01_0001 + (ordinal-1) * 86400000.0 d = JS("""new Date(@{{t}})""") return date(0, 0, 0, d=d) - + def ctime(self): return "%s %s %2d %02d:%02d:%02d %04d" % (__c__days[self._d.getDay()][:3], __c__months[self._d.getMonth()][:3], self._d.getDate(), self._d.getHours(), self._d.getMinutes(), self._d.getSeconds(), self._d.getFullYear()) - + def isocalendar(self): isoyear = isoweeknr = isoweekday = None _d = self._d @@ -50,12 +50,12 @@ def isocalendar(self): } return Math.floor(365.25 * y) - Math.floor(y / 100) + Math.floor(y / 400) + Math.floor(30.6 * (m + 1)) + day - 62; }; - + var year = @{{_d}}.getFullYear(); var month = @{{_d}}.getMonth(); var day = @{{_d}}.getDate(); var wday = @{{_d}}.getDay(); - + @{{isoweekday}} = ((wday + 6) % 7) + 1; @{{isoyear}} = year; @@ -78,13 +78,13 @@ def isocalendar(self): } """) return (isoyear, isoweeknr, isoweekday) - + def isoformat(self): return "%04d-%02d-%02d" % (self.year, self.month, self.day) - + def isoweekday(self): return ((self._d.getDay() + 6) % 7) + 1 - + def replace(self, year=None, month=None, day=None): if year is None: year = self.year @@ -93,18 +93,18 @@ def replace(self, year=None, month=None, day=None): if day is None: day = self.day return date(year, month, day) - + def strftime(self, format): return strftime(format, self.timetuple()) - + def timetuple(self): tm = localtime(int(self._d.getTime() / 1000.0)) tm.tm_hour = tm.tm_min = tm.tm_sec = 0 return tm - + def toordinal(self): return 1 + int((self._d.getTime() - __Jan_01_0001) / 86400000.0) - + def weekday(self): return (self._d.getDay() + 6) % 7 @@ -122,13 +122,13 @@ def __cmp__(self, other): else: raise TypeError("expected date or datetime object") return 1 - + def __add__(self, other): if isinstance(other, timedelta): return date(self.year, self.month, self.day + other.days) else: raise TypeError("expected timedelta object") - + def __sub__(self, other): if isinstance(other, date) or isinstance(other, datetime): diff = self._d.getTime() - other._d.getTime() @@ -151,16 +151,16 @@ def __init__(self, hour, minute=0, second=0, microsecond=0, tzinfo=None, d=None) self.second = d.getSeconds() self.microsecond = d.getMilliseconds() * 1000.0 self.tzinfo = None - + def dst(self): raise NotImplementedError("dst") - + def isoformat(self): t = "%02d:%02d:%02d" % (self.hour, self.minute, self.second) if self.microsecond: t += ".%06d" % self.microsecond return t - + def replace(self, hour=None, minute=None, second=None, microsecond=None, tzinfo=None): if tzinfo != None: raise NotImplementedError("tzinfo") @@ -173,13 +173,13 @@ def replace(self, hour=None, minute=None, second=None, microsecond=None, tzinfo= if microsecond is None: microsecond = self.microsecond return time(hour, minute, second, microsecond) - + def strftime(self, format): return strftime(format, localtime(int(self._d.getTime() / 1000.0))) - + def tzname(self): return None - + def utcoffset(self): return None @@ -193,11 +193,11 @@ def __init__(self, year, month, day, hour=0, minute=0, second=0, microsecond=0, d = JS("""new Date(@{{year}}, @{{month}} - 1, @{{day}}, @{{hour}}, @{{minute}}, @{{second}}, 0.5 + @{{microsecond}} / 1000.0)""") date.__init__(self, 0, 0, 0, d=d) time.__init__(self, 0, d=d) - + @classmethod def combine(self, date, time): return datetime(date.year, date.month, date.day, time.hour, time.minute, time.second, time.microsecond) - + @classmethod def fromtimestamp(self, timestamp, tz=None): if tz != None: @@ -205,45 +205,45 @@ def fromtimestamp(self, timestamp, tz=None): d = JS("""new Date()""") d.setTime(timestamp * 1000.0) return datetime(0, 0, 0, d=d) - + @classmethod def fromordinal(self, ordinal): d = JS("""new Date()""") d.setTime((ordinal - 719163.0) * 86400000.0) return datetime(0, 0, 0, d=d) - + @classmethod def now(self, tz=None): if tz != None: raise NotImplementedError("tz") return datetime(0, 0, 0, d=JS("""new Date()""")) - + @classmethod def strptime(self, datestring, format): return self.fromtimestamp(_strptime(datestring, format)) - + @classmethod def utcfromtimestamp(self, timestamp): tm = gmtime(timestamp) return datetime(tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec) - + @classmethod def utcnow(self): d = JS("""new Date()""") return datetime.utcfromtimestamp(int(d.getTime() / 1000.0)) - + def timetuple(self): return localtime(int(self._d.getTime() / 1000.0)) - + def astimezone(self, tz): raise NotImplementedError("astimezone") - + def date(self): return date(self.year, self.month, self.day) - + def time(self): return time(self.hour, self.minute, self.second, self.microsecond) - + def replace(self, year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, tzinfo=None): if tzinfo != None: raise NotImplementedError("tzinfo") @@ -262,13 +262,13 @@ def replace(self, year=None, month=None, day=None, hour=None, minute=None, secon if microsecond is None: microsecond = self.microsecond return datetime(year, month, day, hour, minute, second, microsecond) - + def timetz(self): raise NotImplementedError("timetz") - + def utctimetuple(self): return gmtime(self._d.getTime() / 1000.0) - + def isoformat(self, sep='T'): t = "%04d-%02d-%02d%s%02d:%02d:%02d" % (self.year, self.month, self.day, sep, self.hour, self.minute, self.second) if self.microsecond: diff --git a/pyjs/src/pyjs/lib/genericpath.py b/pyjs/src/pyjs/lib/genericpath.py index 35659e3ee..a0bf6013e 100644 --- a/pyjs/src/pyjs/lib/genericpath.py +++ b/pyjs/src/pyjs/lib/genericpath.py @@ -1,105 +1,105 @@ -""" -Path operations common to more than one OS -Do not use directly. The OS specific modules import the appropriate -functions from this module themselves. -""" -import os -import stat - -__all__ = ['commonprefix', 'exists', 'getatime', 'getctime', 'getmtime', - 'getsize', 'isdir', 'isfile'] - - -# Does a path exist? -# This is false for dangling symbolic links on systems that support them. -def exists(path): - """Test whether a path exists. Returns False for broken symbolic links""" - try: - os.stat(path) - except os.error: - return False - return True - - -# This follows symbolic links, so both islink() and isdir() can be true -# for the same path ono systems that support symlinks -def isfile(path): - """Test whether a path is a regular file""" - try: - st = os.stat(path) - except os.error: - return False - return stat.S_ISREG(st.st_mode) - - -# Is a path a directory? -# This follows symbolic links, so both islink() and isdir() -# can be true for the same path on systems that support symlinks -def isdir(s): - """Return true if the pathname refers to an existing directory.""" - try: - st = os.stat(s) - except os.error: - return False - return stat.S_ISDIR(st.st_mode) - - -def getsize(filename): - """Return the size of a file, reported by os.stat().""" - return os.stat(filename).st_size - - -def getmtime(filename): - """Return the last modification time of a file, reported by os.stat().""" - return os.stat(filename).st_mtime - - -def getatime(filename): - """Return the last access time of a file, reported by os.stat().""" - return os.stat(filename).st_atime - - -def getctime(filename): - """Return the metadata change time of a file, reported by os.stat().""" - return os.stat(filename).st_ctime - - -# Return the longest prefix of all list elements. -def commonprefix(m): - "Given a list of pathnames, returns the longest common leading component" - if not m: return '' - s1 = min(m) - s2 = max(m) - for i, c in enumerate(s1): - if c != s2[i]: - return s1[:i] - return s1 - -# Split a path in root and extension. -# The extension is everything starting at the last dot in the last -# pathname component; the root is everything before that. -# It is always true that root + ext == p. - -# Generic implementation of splitext, to be parametrized with -# the separators -def _splitext(p, sep, altsep, extsep): - """Split the extension from a pathname. - - Extension is everything from the last dot to the end, ignoring - leading dots. Returns "(root, ext)"; ext may be empty.""" - - sepIndex = p.rfind(sep) - if altsep: - altsepIndex = p.rfind(altsep) - sepIndex = max(sepIndex, altsepIndex) - - dotIndex = p.rfind(extsep) - if dotIndex > sepIndex: - # skip all leading dots - filenameIndex = sepIndex + 1 - while filenameIndex < dotIndex: - if p[filenameIndex] != extsep: - return p[:dotIndex], p[dotIndex:] - filenameIndex += 1 - - return p, '' +""" +Path operations common to more than one OS +Do not use directly. The OS specific modules import the appropriate +functions from this module themselves. +""" +import os +import stat + +__all__ = ['commonprefix', 'exists', 'getatime', 'getctime', 'getmtime', + 'getsize', 'isdir', 'isfile'] + + +# Does a path exist? +# This is false for dangling symbolic links on systems that support them. +def exists(path): + """Test whether a path exists. Returns False for broken symbolic links""" + try: + os.stat(path) + except os.error: + return False + return True + + +# This follows symbolic links, so both islink() and isdir() can be true +# for the same path ono systems that support symlinks +def isfile(path): + """Test whether a path is a regular file""" + try: + st = os.stat(path) + except os.error: + return False + return stat.S_ISREG(st.st_mode) + + +# Is a path a directory? +# This follows symbolic links, so both islink() and isdir() +# can be true for the same path on systems that support symlinks +def isdir(s): + """Return true if the pathname refers to an existing directory.""" + try: + st = os.stat(s) + except os.error: + return False + return stat.S_ISDIR(st.st_mode) + + +def getsize(filename): + """Return the size of a file, reported by os.stat().""" + return os.stat(filename).st_size + + +def getmtime(filename): + """Return the last modification time of a file, reported by os.stat().""" + return os.stat(filename).st_mtime + + +def getatime(filename): + """Return the last access time of a file, reported by os.stat().""" + return os.stat(filename).st_atime + + +def getctime(filename): + """Return the metadata change time of a file, reported by os.stat().""" + return os.stat(filename).st_ctime + + +# Return the longest prefix of all list elements. +def commonprefix(m): + "Given a list of pathnames, returns the longest common leading component" + if not m: return '' + s1 = min(m) + s2 = max(m) + for i, c in enumerate(s1): + if c != s2[i]: + return s1[:i] + return s1 + +# Split a path in root and extension. +# The extension is everything starting at the last dot in the last +# pathname component; the root is everything before that. +# It is always true that root + ext == p. + +# Generic implementation of splitext, to be parametrized with +# the separators +def _splitext(p, sep, altsep, extsep): + """Split the extension from a pathname. + + Extension is everything from the last dot to the end, ignoring + leading dots. Returns "(root, ext)"; ext may be empty.""" + + sepIndex = p.rfind(sep) + if altsep: + altsepIndex = p.rfind(altsep) + sepIndex = max(sepIndex, altsepIndex) + + dotIndex = p.rfind(extsep) + if dotIndex > sepIndex: + # skip all leading dots + filenameIndex = sepIndex + 1 + while filenameIndex < dotIndex: + if p[filenameIndex] != extsep: + return p[:dotIndex], p[dotIndex:] + filenameIndex += 1 + + return p, '' diff --git a/pyjs/src/pyjs/lib/json.py b/pyjs/src/pyjs/lib/json.py index 39f911693..6e7ed8b06 100644 --- a/pyjs/src/pyjs/lib/json.py +++ b/pyjs/src/pyjs/lib/json.py @@ -59,26 +59,26 @@ def decode(self, s): def decodeAsObject(self, s, object_hook=None): return self.jsObjectToPyObject(self.parseJSON(s)) - + def encode(self, obj): return self.toJSONString(obj) def jsObjectToPy(self, obj): JS(""" if (pyjslib.isArray(@{{obj}})) { - for (var i in @{{obj}}) + for (var i in @{{obj}}) @{{obj}}[i] = this.jsObjectToPy(@{{obj}}[i]); return new pyjslib.list(@{{obj}}); } else if (pyjslib.isObject(@{{obj}})) { - for (var i in @{{obj}}) + for (var i in @{{obj}}) @{{obj}}[i]=this.jsObjectToPy(@{{obj}}[i]); return new pyjslib.dict(@{{obj}}); } - + return @{{obj}}; """) - + def jsObjectToPyObject(self, obj): JS(""" if (pyjslib.isArray(@{{obj}})) { @@ -91,22 +91,22 @@ def jsObjectToPyObject(self, obj): var class_name = @{{obj}}["__jsonclass__"][0]; delete @{{obj}}["__jsonclass__"]; var _obj = this.jsObjectToPyObject(@{{obj}}); - + return $pyjs_kwargs_call( null, eval('$pyjs.loaded_modules.' + class_name), null, _obj, [{}] ); } else { - for (var i in @{{obj}}) + for (var i in @{{obj}}) @{{obj}}[i]=this.jsObjectToPyObject(@{{obj}}[i]); return new pyjslib.dict(@{{obj}}); - } + } } - + return @{{obj}}; """) - + # modified to detect pyjslib.list & pyjslib.dict def toJSONString(self, obj): JS(r""" @@ -219,8 +219,8 @@ def parseJSON(self, str): return false; } """) - - + + parser = JSONParser() dumps = getattr(parser, 'encode') loads = getattr(parser, 'decodeAsObject') diff --git a/pyjs/src/pyjs/lib/logging/handlers.py b/pyjs/src/pyjs/lib/logging/handlers.py index 9b39793d4..1cc6ec79d 100644 --- a/pyjs/src/pyjs/lib/logging/handlers.py +++ b/pyjs/src/pyjs/lib/logging/handlers.py @@ -107,7 +107,7 @@ def emit(self, record): headers = {} headers["Host"] = host if self.method == "POST": - self.httpRequest.asyncPost(url, data, self, + self.httpRequest.asyncPost(url, data, self, content_type="application/x-www-form-urlencoded", headers=headers) else: diff --git a/pyjs/src/pyjs/lib/md5.py b/pyjs/src/pyjs/lib/md5.py index 75aa1ce41..60cf2c296 100644 --- a/pyjs/src/pyjs/lib/md5.py +++ b/pyjs/src/pyjs/lib/md5.py @@ -11,7 +11,7 @@ * Permission to use, copy, modify, and distribute this software * and its documentation for any purposes and without * fee is hereby granted provided that this copyright notice - * appears in all copies. + * appears in all copies. * * Of course, this soft is provided "as is" without express or implied * warranty of any kind. @@ -59,7 +59,7 @@ function shl1(a) { a = a % 0x80000000; if (a & 0x40000000 == 0x40000000) { - a -= 0x40000000; + a -= 0x40000000; a *= 2; a += 0x80000000; } else { @@ -92,7 +92,7 @@ if (t2 >= 0) { return (a & t2); } else { - return (a & b); + return (a & b); } } } @@ -112,7 +112,7 @@ if (t2 >= 0) { return ((a | t2) + 0x80000000); } else { - return (a | b); + return (a | b); } } } @@ -132,7 +132,7 @@ if (t2 >= 0) { return ((a ^ t2) + 0x80000000); } else { - return (a ^ b); + return (a ^ b); } } } @@ -144,12 +144,12 @@ /* Here begin the real algorithm */ -var state = new array(4); +var state = new array(4); var count = new array(2); count[0] = 0; - count[1] = 0; -var buffer = new array(64); -var transformBuffer = new array(16); + count[1] = 0; +var buffer = new array(64); +var transformBuffer = new array(16); var digestBits = new array(16); var S11 = 7; @@ -217,15 +217,15 @@ return a; } -function transform(buf, offset) { - var a = 0, b = 0, c = 0, d = 0; +function transform(buf, offset) { + var a = 0, b = 0, c = 0, d = 0; var x = transformBuffer; - + a = state[0]; b = state[1]; c = state[2]; d = state[3]; - + for (i = 0; i < 16; i++) { x[i] = and(buf[i * 4 + offset], 0xFF); for (j = 1; j < 4; j++) { @@ -323,9 +323,9 @@ } }; -this.update = function(b) { +this.update = function(b) { var index, i; - + index = and(shr(count[0],3) , 0x3F); if (count[0] < 0xFFFFFFFF - 7) { count[0] += 8; @@ -342,7 +342,7 @@ this.finish = function() { var bits = new array(8); - var padding; + var padding; var i = 0, index = 0, padLen = 0; for (i = 0; i < 4; i++) { @@ -353,7 +353,7 @@ } index = and(shr(count[0], 3), 0x3F); padLen = (index < 56) ? (56 - index) : (120 - index); - padding = new array(64); + padding = new array(64); padding[0] = 0x80; for (i = 0; i < padLen; i++) { this.update(padding[i]); @@ -366,7 +366,7 @@ for (j = 0; j < 4; j++) { digestBits[i * 4 + j] = and(shr(state[i], (j * 8)) , 0xFF); } - } + } return digestBits; }; diff --git a/pyjs/src/pyjs/lib/random.py b/pyjs/src/pyjs/lib/random.py index 1cea79545..7ff47729d 100644 --- a/pyjs/src/pyjs/lib/random.py +++ b/pyjs/src/pyjs/lib/random.py @@ -218,7 +218,7 @@ def sample(self, population, k): # in selection order so that all sub-slices will also be valid random # samples. This allows raffle winners (the sample) to be partitioned # into grand prize and second place winners (the subslices). - # + # # Members of the population need not be hashable or unique. If the # population contains repeats, then each occurrence is a possible # selection in the sample. @@ -564,12 +564,12 @@ class WichmannHill(Random): def seed(self, a=None): # """Initialize internal state from hashable object. -# +# # None or no argument seeds from current time or from an operating # system specific randomness source if available. -# +# # If a is not None or an int or long, hash(a) is used instead. -# +# # If a is an int or long, a is used directly. Distinct values between # 0 and 27814431486575L inclusive are guaranteed to yield distinct # internal states (this guarantee is specific to the default @@ -640,9 +640,9 @@ def setstate(self, state): def jumpahead(self, n): # """Act as if n calls to random() were made, but quickly. - # + # # n is an int, greater than or equal to 0. - # + # # Example use: If you have 2 threads and know that each will # consume no more than a million random numbers, create two Random # objects r1 and r2, then do diff --git a/pyjs/src/pyjs/lib/re.py b/pyjs/src/pyjs/lib/re.py index 374a22666..f5c00eb3a 100644 --- a/pyjs/src/pyjs/lib/re.py +++ b/pyjs/src/pyjs/lib/re.py @@ -282,8 +282,8 @@ def match(self, string, pos=0, endpos=None): return None else: # Strickly, we shouldn't use string[pos:] - # The '^' pattern character should match at the real beginning of - # the string and at positions just after a newline, but not + # The '^' pattern character should match at the real beginning of + # the string and at positions just after a newline, but not # necessarily at the index where the search is to start. # Maybe, we should raise an error if there's a '^' in pat (not in []) groups = self.match_code.Exec(string[pos:]) diff --git a/pyjs/src/pyjs/lib/sys.py b/pyjs/src/pyjs/lib/sys.py index c1df94146..541e2a3c3 100644 --- a/pyjs/src/pyjs/lib/sys.py +++ b/pyjs/src/pyjs/lib/sys.py @@ -157,7 +157,7 @@ def write(self, output): def sys_init(): global stdout stdout = _StdStream() - + global stderr stderr = _StdStream() diff --git a/pyjs/src/pyjs/lib/sys.pyv8.py b/pyjs/src/pyjs/lib/sys.pyv8.py index ee318bd42..bf632825e 100644 --- a/pyjs/src/pyjs/lib/sys.pyv8.py +++ b/pyjs/src/pyjs/lib/sys.pyv8.py @@ -1,16 +1,16 @@ # Initialize system values def sys_init(): - + def pyv8_list(l): l2 = list() for i in range(l.__len__()): - l2[0:0] = [l.pop()] + l2[0:0] = [l.pop()] return l2 - + global stdin stdin = pyv8_sys_get_stdin() - + global stdout stdout = pyv8_sys_get_stdout() diff --git a/pyjs/src/pyjs/lib/test/UnitTest.py b/pyjs/src/pyjs/lib/test/UnitTest.py index 5274b7e74..65b97644c 100644 --- a/pyjs/src/pyjs/lib/test/UnitTest.py +++ b/pyjs/src/pyjs/lib/test/UnitTest.py @@ -32,7 +32,7 @@ def _run_test(self, test_method_name): test_method=getattr(self, test_method_name) self.current_test_name = test_method_name self.setUp() - try: + try: try: test_method() except Exception,e: @@ -81,12 +81,12 @@ def getNameFmt(self, msg=""): msg=" " + str(msg) if self.current_test_name: msg += " (%s) " % self.getCurrentTestID() - return self.getName() + msg + ": " + return self.getName() + msg + ": " return "" def getCurrentTestID(self): return "%s/%i" % (self.current_test_name,self.tests_completed) - + def getTestMethods(self): self.test_methods=[] diff --git a/pyjs/src/pyjs/lib/time.py b/pyjs/src/pyjs/lib/time.py index 7dbd55cca..de51faa5c 100644 --- a/pyjs/src/pyjs/lib/time.py +++ b/pyjs/src/pyjs/lib/time.py @@ -69,13 +69,13 @@ def __repr__(self): return self.__str__() def __getitem__(self, idx): - return [self.tm_year, self.tm_mon, self.tm_mday, - self.tm_hour, self.tm_min, self.tm_sec, + return [self.tm_year, self.tm_mon, self.tm_mday, + self.tm_hour, self.tm_min, self.tm_sec, self.tm_wday, self.tm_yday, self.tm_isdst][idx] def __getslice__(self, lower, upper): - return [self.tm_year, self.tm_mon, self.tm_mday, - self.tm_hour, self.tm_min, self.tm_sec, + return [self.tm_year, self.tm_mon, self.tm_mday, + self.tm_hour, self.tm_min, self.tm_sec, self.tm_wday, self.tm_yday, self.tm_isdst][lower:upper] def gmtime(t=None): diff --git a/pyjs/src/pyjs/lib/urlparse.py b/pyjs/src/pyjs/lib/urlparse.py index 19d802a4f..c5104712d 100644 --- a/pyjs/src/pyjs/lib/urlparse.py +++ b/pyjs/src/pyjs/lib/urlparse.py @@ -102,7 +102,7 @@ def __eq__(self, e): if hasattr(e, '_tuple'): e = e._tuple return self._tuple == e def __ne__(self, e): return not self.__eq__(e) - + diff --git a/pyjs/src/pyjs/lib_trans/pycompiler/ast.py b/pyjs/src/pyjs/lib_trans/pycompiler/ast.py index d937b39ae..6efaaa6bf 100644 --- a/pyjs/src/pyjs/lib_trans/pycompiler/ast.py +++ b/pyjs/src/pyjs/lib_trans/pycompiler/ast.py @@ -41,7 +41,7 @@ def _set_lineno(self, lineno): self._lineno = lineno self._context = None lineno = property(_get_lineno, _set_lineno) - + def __str__(self): return repr(self) @@ -593,7 +593,7 @@ def getChildNodes(self): def __repr__(self): return "Function(%s, %s, %s, %s, %s, %s, %s, %s)" % (repr(self.decorators), repr(self.name), repr(self.argnames), repr(self.defaults), repr(self.varargs), repr(self.kwargs), repr(self.doc), repr(self.code)) - + _Function = Function class GenExpr(Node): diff --git a/pyjs/src/pyjs/lib_trans/pycompiler/pyassem.py b/pyjs/src/pyjs/lib_trans/pycompiler/pyassem.py index 8380392ae..5d1ac1d2e 100644 --- a/pyjs/src/pyjs/lib_trans/pycompiler/pyassem.py +++ b/pyjs/src/pyjs/lib_trans/pycompiler/pyassem.py @@ -141,7 +141,7 @@ def fixupOrderHonorNext(self, blocks, default_next): for j, b in l: del blocks[index[b]] # Insert the chain in the proper location - blocks = blocks[:i] + [cur] + [chain] + blocks[i + 1:] + blocks = blocks[:i] + [cur] + [chain] + blocks[i + 1:] # Finally, re-compute the block indexes for i in range(len(blocks)): index[blocks[i]] = i diff --git a/pyjs/src/pyjs/lib_trans/pycompiler/pycodegen.py b/pyjs/src/pyjs/lib_trans/pycompiler/pycodegen.py index fd5aa1e21..3f5ad9c30 100644 --- a/pyjs/src/pyjs/lib_trans/pycompiler/pycodegen.py +++ b/pyjs/src/pyjs/lib_trans/pycompiler/pycodegen.py @@ -487,7 +487,7 @@ def visitFor(self, node): def visitBreak(self, node): if not self.setups: - raise SyntaxError("'break' outside loop (%s, %d)" % + raise SyntaxError("'break' outside loop (%s, %d)" % (node.filename, node.lineno)) self.set_lineno(node) self.emit('BREAK_LOOP') diff --git a/pyjs/src/pyjs/lib_trans/pycompiler/transformer.py b/pyjs/src/pyjs/lib_trans/pycompiler/transformer.py index e13572d2c..c10b86002 100644 --- a/pyjs/src/pyjs/lib_trans/pycompiler/transformer.py +++ b/pyjs/src/pyjs/lib_trans/pycompiler/transformer.py @@ -148,7 +148,7 @@ def parsefile(self, file): def compile_node(self, node): ### emit a line-number node? - + import sys n = node.type @@ -1351,7 +1351,7 @@ def com_subscriptlist(self, primary, nodelist, assigning): isinstance(sub, Sliceobj))] if len(tulplesub) == len(subscripts): subscripts = [Tuple(subscripts)] - elif (len(nodelist.children) == 2 and + elif (len(nodelist.children) == 2 and nodelist.children[1].type == token.COMMA): subscripts = [Tuple(subscripts)] return Subscript(primary, assigning, subscripts, diff --git a/pyjs/src/pyjs/lib_trans/pyparser/__init__.py b/pyjs/src/pyjs/lib_trans/pyparser/__init__.py index 154a87c8a..d2c396c11 100644 --- a/pyjs/src/pyjs/lib_trans/pyparser/__init__.py +++ b/pyjs/src/pyjs/lib_trans/pyparser/__init__.py @@ -10,4 +10,4 @@ def suite(text): # dummy def st2tuple(tree, line_info=1): return tree - + diff --git a/pyjs/src/pyjs/lib_trans/pyparser/grammar2x.py b/pyjs/src/pyjs/lib_trans/pyparser/grammar2x.py index 0517d3e20..76da14903 100644 --- a/pyjs/src/pyjs/lib_trans/pyparser/grammar2x.py +++ b/pyjs/src/pyjs/lib_trans/pyparser/grammar2x.py @@ -1,4 +1,4 @@ -# This module is automatically generated from grammar2x.py.templ, +# This module is automatically generated from grammar2x.py.templ, # at 2011-07-01 13:23:21.288018, with python 2.7.2 (default, Jun 27 2011, 21:15:33) . # # Modified by Daniel Kluev, for Pyjamas project, 2011. diff --git a/pyjs/src/pyjs/lib_trans/test/UnitTest.py b/pyjs/src/pyjs/lib_trans/test/UnitTest.py index 9ebdc5291..5405d4a87 100644 --- a/pyjs/src/pyjs/lib_trans/test/UnitTest.py +++ b/pyjs/src/pyjs/lib_trans/test/UnitTest.py @@ -32,7 +32,7 @@ def _run_test(self, test_method_name): test_method=getattr(self, test_method_name) self.current_test_name = test_method_name self.setUp() - try: + try: try: test_method() except Exception, e: @@ -83,12 +83,12 @@ def getNameFmt(self, msg=""): msg=" " + str(msg) if self.current_test_name: msg += " (%s) " % self.getCurrentTestID() - return self.getName() + msg + ": " + return self.getName() + msg + ": " return "" def getCurrentTestID(self): return "%s/%i" % (self.current_test_name,self.tests_completed) - + def getTestMethods(self): self.test_methods=[] diff --git a/pyjs/src/pyjs/lib_trans/test/test_compiler.py b/pyjs/src/pyjs/lib_trans/test/test_compiler.py index 4ff18094c..8d7249211 100644 --- a/pyjs/src/pyjs/lib_trans/test/test_compiler.py +++ b/pyjs/src/pyjs/lib_trans/test/test_compiler.py @@ -21,18 +21,18 @@ def test_statements(self): statements = [ ("a + 1", "Stmt([Discard(Add(Name('a'), Const(1)))])"), - + ("a = 1", "Stmt([Assign([AssName('a', 'OP_ASSIGN')], Const(1))])"), - + ("def test(): pass", "Stmt([Function(None, 'test', (), (), False," " False, None, Stmt([Pass()]))])"), - + ("with a as b: pass", "Stmt([With(Name('a'), AssName('b', 'OP_ASSIGN')," " Stmt([Pass()]))])"), - + (""" def test(a, b=123, **kw): yield b @@ -40,7 +40,7 @@ def test(a, b=123, **kw): "Stmt([Function(None, 'test', ['a', 'b', 'kw']," " [Const(123)], False, True, None," " Stmt([Discard(Yield(Name('b')))]))])"), - + (""" @dec class X(object): @@ -48,7 +48,7 @@ class X(object): """, "Stmt([Class('X', [Name('object')], None," " Stmt([Pass()]), Decorators([Name('dec')]))])"), - + (""" @dec() def test(): @@ -56,7 +56,7 @@ def test(): """, "Stmt([Function(Decorators([CallFunc(Name('dec'), [], None, None)])," " 'test', (), (), False, False, None, Stmt([Pass()]))])"), - + (""" try: 1//0 @@ -70,17 +70,17 @@ def test(): "[(None, None, Stmt([Assign([AssName('e', 'OP_ASSIGN')], " "Const(1))]))], None), Stmt([Assign([AssName('f', 'OP_ASSIGN')], " "Const(1))]))])"), - + (""" "doc" - + def test(): "doc" pass """, "Stmt([Function(None, 'test', (), (), False, " "False, 'doc', Stmt([Pass()]))])"), - + (""" def g(): a = 1 @@ -95,20 +95,20 @@ def f(): return a + 2 "Return(CallFunc(Name('f'), [], None, None))])), " "Assign([AssName('result', 'OP_ASSIGN')], " "CallFunc(Name('g'), [], None, None))])"), - + #(""" #list((i,j) for i in range(3) if i < 3 # for j in range(4) if j > 2) #""", # "Stmt([Discard(CallFunc(Name('list'), [GenExpr(GenExprInner(Tuple([Name('i'), Name('j')]), [GenExprFor(AssName('i', 'OP_ASSIGN'), CallFunc(Name('range'), [Const(3)], None, None), [GenExprIf(Compare(Name('i'), [('<', Const(3))]))]), GenExprFor(AssName('j', 'OP_ASSIGN'), CallFunc(Name('range'), [Const(4)], None, None), [GenExprIf(Compare(Name('j'), [('>', Const(2))]))])]))], None, None))])"), - + (""" {1, 2, 3} {1, 2, 3,} """, 'Stmt([Discard(Set([Const(1), Const(2), Const(3)])), ' 'Discard(Set([Const(1), Const(2), Const(3)]))])'), - + (""" {1:2, 2:3, 3:4} {1:2, 2:3, 3:4,} @@ -117,7 +117,7 @@ def f(): return a + 2 '(Const(2), Const(3)), (Const(3), Const(4))])), ' 'Discard(Dict([(Const(1), Const(2)), (Const(2), Const(3)), ' '(Const(3), Const(4))]))])'), - + #(""" #{x for x in range(1, 4)} #""", @@ -125,7 +125,7 @@ def f(): return a + 2 # "[ListCompFor(AssName('x', 'OP_ASSIGN'), " # "CallFunc(Name('range'), " # "[Const(1), Const(4)], None, None), [])]))])"), - + #(""" #{x:x+1 for x in range(1, 4)} #""", @@ -133,7 +133,7 @@ def f(): return a + 2 # "[ListCompFor(AssName('x', 'OP_ASSIGN'), " # "CallFunc(Name('range'), " # "[Const(1), Const(4)], None, None), [])]))])"), - + (""" with Ctx(1) as tc, Ctx(2) as tc2: pass @@ -142,14 +142,14 @@ def f(): return a + 2 "AssName('tc', 'OP_ASSIGN'), " "With(CallFunc(Name('Ctx'), [Const(2)], None, None), " "AssName('tc2', 'OP_ASSIGN'), Stmt([Pass()])))])"), - + (""" global x x = 1 """, "Stmt([Global(['x']), " "Assign([AssName('x', 'OP_ASSIGN')], Const(1))])"), - + (""" print 'a', 'b' print 'a', @@ -157,7 +157,7 @@ def f(): return a + 2 """, "Stmt([Printnl([Const('a'), Const('b')], None, True), " "Print([Const('a')], None), " - "Printnl([Tuple([Const('a'), Const('b')])], None, True)])"), + "Printnl([Tuple([Const('a'), Const('b')])], None, True)])"), #(""" #a = 1 + 1j @@ -165,21 +165,21 @@ def f(): return a + 2 #""", # "Stmt([Assign([AssName('a', 'OP_ASSIGN')], " # "Add(Const(1), Const(1j))), " - # "Assign([AssName('b', 'OP_ASSIGN')], Const(1.2356))])"), - + # "Assign([AssName('b', 'OP_ASSIGN')], Const(1.2356))])"), + (""" [1,2,3][1:2:3] """, "Stmt([Discard(Subscript(List([Const(1), Const(2), Const(3)]), " - "'OP_APPLY', [Sliceobj([Const(1), Const(2), Const(3)])]))])"), - + "'OP_APPLY', [Sliceobj([Const(1), Const(2), Const(3)])]))])"), + (""" x.a.b.c()().__z__ """, "Stmt([Discard(Getattr(CallFunc(CallFunc" "(Getattr(Getattr(Getattr(Name('x'), 'a'), 'b'), 'c'), " - "[], None, None), [], None, None), '__z__'))])"), - + "[], None, None), [], None, None), '__z__'))])"), + (""" # comment1 class X(): @@ -194,7 +194,7 @@ class Z(): "Stmt([Assign([AssName('z', 'OP_ASSIGN')], Const(1))]), None), " "Assign([AssName('x', 'OP_ASSIGN')], Const(2))]), None)])"), ] - + for code, codestr in statements: self._test_compile(code, codestr) diff --git a/pyjs/src/pyjs/linker.py b/pyjs/src/pyjs/linker.py index aa8d7b9b2..872d1658a 100644 --- a/pyjs/src/pyjs/linker.py +++ b/pyjs/src/pyjs/linker.py @@ -28,20 +28,20 @@ -translator_opts = [ 'debug', - 'print_statements', - 'internal_ast', - 'function_argument_checking', - 'attribute_checking', - 'bound_methods', - 'descriptors', - 'source_tracking', - 'stupid_mode', - 'line_tracking', - 'store_source', - 'inline_code', - 'operator_funcs ', - 'number_classes', +translator_opts = [ 'debug', + 'print_statements', + 'internal_ast', + 'function_argument_checking', + 'attribute_checking', + 'bound_methods', + 'descriptors', + 'source_tracking', + 'stupid_mode', + 'line_tracking', + 'store_source', + 'inline_code', + 'operator_funcs ', + 'number_classes', 'list_imports', 'translator', ] @@ -137,7 +137,7 @@ def out_translate(platform, file_names, out_file, module_name, opts = [pyjs.PYTHON] + [os.path.join(pydir, translate_cmd)] + translate_cmd_opts + opts pyjscompile_cmd = '"%s"' % '" "'.join(opts) - + proc = subprocess.Popen(pyjscompile_cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, @@ -160,7 +160,7 @@ def out_translate(platform, file_names, out_file, module_name, #print "translate", out_file, deps, js_libs, stdout_value return deps, js_libs - + _path_cache= {} def module_path(name, path, platform=None): if name == '__pyjamas__' or name == '__javascript__': @@ -218,7 +218,7 @@ def module_path(name, path, platform=None): if p in _path_cache[name] and not _path_cache[name][p] is None: return _path_cache[name][p] _path_cache[name][p] = None - + return None raise RuntimeError, "Module %r not found" % name @@ -229,7 +229,7 @@ class BaseLinker(object): def __init__(self, modules, output='output', compiler=None, - debug=False, + debug=False, js_libs=[], static_js_libs=[], early_static_js_libs=[], late_static_js_libs=[], dynamic_js_libs=[], early_static_app_libs = [], unlinked_modules = [], keep_lib_files = False, platforms=[], path=[], @@ -352,7 +352,7 @@ def visit_module(self, file_path, overrides, platform, module_name + plat_suffix + pyjs.MOD_SUFFIX) if out_file in self.done.get(platform, []): return - + # translate if # - no platform # - or if we have an override diff --git a/pyjs/src/pyjs/translator_dict.py b/pyjs/src/pyjs/translator_dict.py index d2bc3c802..fa302cf55 100644 --- a/pyjs/src/pyjs/translator_dict.py +++ b/pyjs/src/pyjs/translator_dict.py @@ -1838,8 +1838,8 @@ def node_file_input(self, node): ++ %(globals)s['__builtins__'] = %(module_store)s[%(__builtin__)r] ++ %(track)s['module'] = $name;""" % jsvars) if jsvars['module_name'] != jsvars['__builtin__']: - # Add builtins to the module object _and_ the globals. On - # deletion of a global, the builtin (if any) has to be + # Add builtins to the module object _and_ the globals. On + # deletion of a global, the builtin (if any) has to be # copied back from module to global. # TODO: restrict the number of 'copied' builtins self.add_lines("""\ @@ -2107,7 +2107,7 @@ def flatten_arg(names): locals_init.append( "%s['%s'] = $%s;" % ( jsvars['locals'], - arg, + arg, arg, ) ) @@ -2446,7 +2446,7 @@ def node_not_test(self, node, jsbool=False, name=None): jsvars.update(locals()) if jsbool: return "%(builtin)s['test_not'](%(value)s)" % jsvars - + return "%(builtin)s['op_not'](%(value)s)" % jsvars self.not_implemented(node) @@ -3122,7 +3122,7 @@ def leaf_return(self, leaf): ### from options import (all_compile_options, add_compile_options, - get_compile_options, debug_options, speed_options, + get_compile_options, debug_options, speed_options, pythonic_options) if os.environ.has_key('PYJS_SYSPATH'): diff --git a/pyjs/src/pyjs/translator_proto-KEES.py b/pyjs/src/pyjs/translator_proto-KEES.py index dc279019c..585dae461 100644 --- a/pyjs/src/pyjs/translator_proto-KEES.py +++ b/pyjs/src/pyjs/translator_proto-KEES.py @@ -27,7 +27,7 @@ import compiler from compiler.visitor import ASTVisitor from options import (all_compile_options, add_compile_options, - get_compile_options, debug_options, speed_options, + get_compile_options, debug_options, speed_options, pythonic_options) escaped_subst = re.compile('@{{(!?[ a-zA-Z0-9_\.]*)}}') @@ -764,7 +764,7 @@ def __init__(self, compiler, self.output = output self.dynamic = dynamic self.findFile = findFile - + self.set_compile_options(kw) # compile options @@ -937,7 +937,7 @@ def __init__(self, compiler, self.w( '/*') self.w( 'PYJS_JS: %s' % repr(self.imported_js)) self.w( '*/') - + def set_compile_options(self, opts): opts = dict(all_compile_options, **opts) for opt, value in opts.iteritems(): @@ -945,7 +945,7 @@ def set_compile_options(self, opts): setattr(self, opt, value) else: raise Exception("Translator got an unknown option %s" % opt) - + self.ignore_debug = False self.inline_bool = self.inline_code self.inline_len = self.inline_code @@ -953,7 +953,7 @@ def set_compile_options(self, opts): self.inline_cmp = self.inline_code self.inline_getitem = self.inline_code if self.number_classes: - self.operator_funcs = True + self.operator_funcs = True def w(self, txt, newline=True, output=None, translate=True): if translate and txt: @@ -2025,8 +2025,8 @@ def _doImport(self, names, current_klass, root_level, assignBase, importName, context, self.modpfx()[:-1], - ) - + ) + if not assignBase: self.w( self.spacing() + import_stmt + ', null, false);') self._lhsFromName(importName, current_klass, modtype) diff --git a/pyjs/src/pyjs/translator_proto-KLUEV.py b/pyjs/src/pyjs/translator_proto-KLUEV.py index 24afa5867..4b7b9c631 100644 --- a/pyjs/src/pyjs/translator_proto-KLUEV.py +++ b/pyjs/src/pyjs/translator_proto-KLUEV.py @@ -27,7 +27,7 @@ import logging from options import (all_compile_options, add_compile_options, - get_compile_options, debug_options, speed_options, + get_compile_options, debug_options, speed_options, pythonic_options) if os.environ.has_key('PYJS_SYSPATH'): @@ -385,7 +385,7 @@ "tuple", "complex", "slice", - + "Ellipsis", # atom ] @@ -720,7 +720,7 @@ class Translator(object): 'noNumberClasses': [('number_classes', False)], 'NumberClasses': [('number_classes', True)], } - + pyjslib_prefix = "$p" def __init__(self, compiler, @@ -743,7 +743,7 @@ def __init__(self, compiler, self.output = output self.dynamic = dynamic self.findFile = findFile - + self.set_compile_options(kw) # compile options @@ -792,8 +792,8 @@ def __init__(self, compiler, self.w( self.spacing() + "if(" "typeof $pyjs.loaded_modules['%(parent_module)s'] == 'undefined' ||" " !$pyjs.loaded_modules['%(parent_module)s'].__was_initialized__)" - " %(___import___)s('%(parent_module)s', null);" % - dict(parent_module = self.parent_module_name, + " %(___import___)s('%(parent_module)s', null);" % + dict(parent_module = self.parent_module_name, ___import___ = self.pyjslib_name('___import___') )) parts = self.js_module_name.split('.') @@ -807,10 +807,10 @@ def __init__(self, compiler, self.w( self.spacing() + self.module_prefix + '__repr__ = function() { return "<module: %s>"; };' % (module_name)) self.w( self.spacing() + self.module_prefix + "__was_initialized__ = true;") self.w( self.spacing() + self.module_prefix + "__builtins__ = $pyjs.loaded_modules['pyjslib'];") - # XXX: Docstrings could be useful sometimes, maybe introduce flag for + # XXX: Docstrings could be useful sometimes, maybe introduce flag for # keeping them intact? self.w( self.spacing() + self.module_prefix + "__doc__ = null;") - + self.w( self.spacing() + "if ((__mod_name__ === null) || (typeof __mod_name__ == 'undefined')) __mod_name__ = '%s';" % (module_name)) lhs = self.scopeName('__name__', 0, False) self.w( self.spacing() + "%s = __mod_name__;" % (lhs)) @@ -909,9 +909,9 @@ def __init__(self, compiler, self.w( captured_output, False) if attribute_checking: - self.w(self.dedent() + - "} catch ($pyjs_attr_err) {throw " + - self.pyjslib_name('_errorMapping') + + self.w(self.dedent() + + "} catch ($pyjs_attr_err) {throw " + + self.pyjslib_name('_errorMapping') + "($pyjs_attr_err);};" ) @@ -932,7 +932,7 @@ def __init__(self, compiler, self.w( '/*') self.w( 'PYJS_JS: %s' % repr(self.imported_js)) self.w( '*/') - + def set_compile_options(self, opts): opts = dict(all_compile_options, **opts) for opt, value in opts.iteritems(): @@ -940,7 +940,7 @@ def set_compile_options(self, opts): setattr(self, opt, value) else: raise Exception("Translator got an unknown option %s" % opt) - + self.ignore_debug = False self.inline_bool = self.inline_code self.inline_len = self.inline_code @@ -948,7 +948,7 @@ def set_compile_options(self, opts): self.inline_cmp = self.inline_code self.inline_getitem = self.inline_code if self.number_classes: - self.operator_funcs = True + self.operator_funcs = True def w(self, txt, newline=True, output=None, translate=True): if translate and txt: @@ -1064,7 +1064,7 @@ def add_callfunc(code, d, generic=True): self.pop_lookup() if code != '%s': - # XXX: Why is it here? It adds staticmethod to ANY decorated func, + # XXX: Why is it here? It adds staticmethod to ANY decorated func, # Even if its not method! code = code % ("@"+"{{staticmethod}}(%s)") if staticmethod: @@ -1124,7 +1124,7 @@ def jsname(self, name_type, jsname): if len(words) == 0: return words[0] return self.attrib_join(words) - + def pyjslib_name(self, name, args=None): if args is None: return "$p['" + name + "']" @@ -1752,7 +1752,7 @@ def _instance_method_init(self, node, arg_names, varargname, kwargname, %(s)s\t\t} %(s)s\t} %(s)s}\ -""" % {'s': self.spacing(), 'self': arg_names[0], +""" % {'s': self.spacing(), 'self': arg_names[0], '_isinstance': self.pyjslib_name('_isinstance'), '__md5__': current_klass.__md5__}, output=output) @@ -2035,12 +2035,12 @@ def _doImport(self, names, current_klass, root_level, assignBase, ) else: import_stmt = "%s('%s', %s, %s" %( - self.pyjslib_name('__import_all__'), + self.pyjslib_name('__import_all__'), importName, context, self.modpfx()[:-1], - ) - + ) + if not assignBase: self.w( self.spacing() + import_stmt + ', null, false);') self._lhsFromName(importName, current_klass, modtype) @@ -2272,7 +2272,7 @@ def _assert(self, node, current_klass): else: fail = '' self.w( self.spacing() + "if (!( " + expr + " )) {") - self.w( self.spacing() + " throw %(AssertionError)s(%(fail)s);" % + self.w( self.spacing() + " throw %(AssertionError)s(%(fail)s);" % dict(AssertionError=self.pyjslib_name('AssertionError'), fail=fail)) self.w( self.spacing() + " }") @@ -2555,7 +2555,7 @@ def _tryExcept(self, node, current_klass): self.w( self.dedent() + """} else {""") self.indent() if self.attribute_checking: - self.w( self.spacing() + + self.w( self.spacing() + """%(try_err)s = %(_errorMapping)s(%(try_err)s);""" % dict( try_err=pyjs_try_err, _errorMapping=self.pyjslib_name('_errorMapping') @@ -2669,7 +2669,7 @@ def _tryExcept(self, node, current_klass): self.stacksize_depth -= 1 self.generator_switch_case(increment=True) self.is_generator = save_is_generator - + def _with(self, v, current_klass): """ http://www.python.org/dev/peps/pep-0343/ @@ -2687,14 +2687,14 @@ def _with(self, v, current_klass): save_output = self.output self.output = StringIO() self.indent() - + for node in body_nodes: self._stmt(node, current_klass) - + self.dedent() captured_output = self.output self.output = save_output - + self.w(self.spacing() + "%(__with)s(%(expr)s, function(%(withvar)s){" % dict(expr=expr, __with=self.pyjslib_name('__with'), @@ -2709,7 +2709,7 @@ def _getattr(self, v, current_klass, use_getattr=None): attr_name = self.attrib_remap(v.attrname) if use_getattr: expr = self.expr(v.expr, current_klass) - return [self.pyjslib_name("getattr", + return [self.pyjslib_name("getattr", args="%s, '%s'" % (expr, attr_name))] if isinstance(v.expr, self.ast.Name): @@ -2717,7 +2717,7 @@ def _getattr(self, v, current_klass, use_getattr=None): if not use_getattr or attr_name == '__class__' or \ attr_name == '__name__': return [obj, attr_name] - return [self.pyjslib_name("getattr", + return [self.pyjslib_name("getattr", args="%s, '%s'" % (obj, attr_name))] elif isinstance(v.expr, self.ast.Getattr): return self._getattr(v.expr, current_klass) + [attr_name] @@ -2841,9 +2841,9 @@ def _class(self, node, parent_class = None): %(s)svar $data = $p['dict'](); %(s)sfor (var $item in %(local_prefix)s) { $data.__setitem__($item, %(local_prefix)s[$item]); } %(s)sreturn %(_create_class)s('%(n)s', $p['tuple']($bases), $data);""" - create_class %= {'n': node.name, 's': self.spacing(), + create_class %= {'n': node.name, 's': self.spacing(), '_create_class':self.pyjslib_name('_create_class'), - 'local_prefix': local_prefix, + 'local_prefix': local_prefix, 'bases': ",".join(map(lambda x: x[1], base_classes)) } create_class += """ @@ -3308,15 +3308,15 @@ def _lhsFromAttr(self, v, current_klass): raise TranslationError( "unsupported type (in _assign)", v.expr, self.module_name) return lhs - + def _assigns_list(self, v, current_klass, expr): """ Handles all kinds of assignments for Assign, For and so on. - + expr is string representing expr to assign, i.e. self.expr() result - + Calls itself recursively for AssTuple - + Returns list of JS strings """ assigns = [] @@ -3332,7 +3332,7 @@ def _assigns_list(self, v, current_klass, expr): desc_setattr = ("""%(l)s.__is_instance__ && """ """typeof %(l)s.__setattr__ == 'function' ? """ """%(l)s.__setattr__('%(a)s', %(r)s) : """ - """%(setattr)s(%(l)s, '%(a)s', %(r)s); """ % + """%(setattr)s(%(l)s, '%(a)s', %(r)s); """ % dict( setattr=self.pyjslib_name('setattr'), l=lhs, @@ -3373,7 +3373,7 @@ def _assigns_list(self, v, current_klass, expr): upper = self.expr(v.upper, current_klass) obj = self.expr(v.expr, current_klass) assigns.append(self.track_call( - self.pyjslib_name("__setslice", + self.pyjslib_name("__setslice", args=[obj, lower, upper, expr]), v.lineno) + ';') return assigns @@ -3389,20 +3389,20 @@ def _assigns_list(self, v, current_klass, expr): """ child_nodes = v.getChildNodes() extended_unpack = 'null' - - # Grammar and parser do not support extended unpack yet, + + # Grammar and parser do not support extended unpack yet, # should check each child and assign index if found extended flag for child in child_nodes: pass - + tempName = self.uniqid("$tupleassign") unpack_call = self.track_call( - self.pyjslib_name('__ass_unpack', + self.pyjslib_name('__ass_unpack', args=[expr, len(child_nodes), extended_unpack] ), v.lineno) - + assigns.append("var " + tempName + " = " + unpack_call + ";") - + for index,child in enumerate(child_nodes): unpacked_value = tempName + "[" + str(index) + "]"; assigns.extend(self._assigns_list(child, current_klass, unpacked_value)) @@ -3459,7 +3459,7 @@ def _discard(self, node, current_klass): # XXX: should trigger exceptions if expr resolves to undefined expr = self.expr(node.expr, current_klass) self.w(self.spacing() + expr + ";") - + # Never happens #raise TranslationError( # "unsupported type, must be call or const (in _discard)", node.expr, self.module_name) @@ -3652,7 +3652,7 @@ def _for(self, node, current_klass): else: assTestvar = "" reuse_tuple = "false" - + if self.inline_code: rhs = nextval else: @@ -3705,7 +3705,7 @@ def _for(self, node, current_klass): self.generator_add_state() self.generator_switch_open() self.generator_switch_case(increment=False) - + for line in assigns: self.w( self.spacing() + line) @@ -3857,7 +3857,7 @@ def _sub(self, node, current_klass): if self.inline_code: return """(typeof (%(v1)s=%(e1)s)==typeof (%(v2)s=%(e2)s) && (typeof %(v1)s=='number'||typeof %(v1)s=='string')? %(s)s\t%(v1)s-%(v2)s: -%(s)s\t%(op_sub)s(%(v1)s,%(v2)s))""" % dict(locals(), +%(s)s\t%(op_sub)s(%(v1)s,%(v2)s))""" % dict(locals(), op_sub=self.pyjslib_name('op_sub')) return """%(__op_sub)s(%(v1)s=%(e1)s,%(v2)s=%(e2)s)""" % dict( locals(), __op_sub=self.pyjslib_name('__op_sub')) @@ -3889,7 +3889,7 @@ def _div(self, node, current_klass): s = self.spacing() if self.future_division: op_div = self.pyjslib_name('op_truediv') - else: + else: op_div = self.pyjslib_name('op_div') return """(typeof (%(v1)s=%(e1)s)==typeof (%(v2)s=%(e2)s) && typeof %(v1)s=='number' && %(v2)s !== 0? %(s)s\t%(v1)s/%(v2)s: @@ -3913,7 +3913,7 @@ def _mul(self, node, current_klass): def _mod(self, node, current_klass): if isinstance(node.left, self.ast.Const) and isinstance(node.left.value, StringType): return self.track_call( - self.pyjslib_name("sprintf", + self.pyjslib_name("sprintf", args=[self.expr(node.left, current_klass), self.expr(node.right, current_klass)] ), node.lineno) @@ -3952,13 +3952,13 @@ def _power(self, node, current_klass): def _invert(self, node, current_klass): if not self.operator_funcs or not self.number_classes: return "~(%s)" % self.expr(node.expr, current_klass) - return self.pyjslib_name("op_invert", + return self.pyjslib_name("op_invert", args=self.expr(node.expr, current_klass)) def _bitshiftleft(self, node, current_klass): if not self.operator_funcs or not self.number_classes: return "(%s)<<(%s)"% (self.expr(node.left, current_klass), self.expr(node.right, current_klass)) - return self.pyjslib_name("op_bitshiftleft", + return self.pyjslib_name("op_bitshiftleft", args=[ self.expr(node.left, current_klass), self.expr(node.right, current_klass) @@ -3968,7 +3968,7 @@ def _bitshiftright(self, node, current_klass): if not self.operator_funcs or not self.number_classes: return "(%s)>>(%s)" % (self.expr(node.left, current_klass), self.expr(node.right, current_klass)) return self.pyjslib_name("op_bitshiftright", args=[ - self.expr(node.left, current_klass), + self.expr(node.left, current_klass), self.expr(node.right, current_klass) ]) @@ -3977,10 +3977,10 @@ def _bitand(self, node, current_klass): return "(%s)" % ")&(".join([self.expr(child, current_klass) for child in node.nodes]) if len(node.nodes) == 2: return self.pyjslib_name("op_bitand2", args=[ - self.expr(node.nodes[0], current_klass), + self.expr(node.nodes[0], current_klass), self.expr(node.nodes[1], current_klass)]) - return self.pyjslib_name("op_bitand", - args="[%s]" % + return self.pyjslib_name("op_bitand", + args="[%s]" % ", ".join([self.expr(child, current_klass) for child in node.nodes]) ) @@ -3989,9 +3989,9 @@ def _bitxor(self,node, current_klass): return "(%s)" % ")^(".join([self.expr(child, current_klass) for child in node.nodes]) if len(node.nodes) == 2: return self.pyjslib_name("op_bitxor2", args=[ - self.expr(node.nodes[0], current_klass), + self.expr(node.nodes[0], current_klass), self.expr(node.nodes[1], current_klass)]) - return self.pyjslib_name("op_bitxor", args="[%s]" % + return self.pyjslib_name("op_bitxor", args="[%s]" % ", ".join([self.expr(child, current_klass) for child in node.nodes]) ) @@ -4000,9 +4000,9 @@ def _bitor(self, node, current_klass): return "(%s)" % ")|(".join([self.expr(child, current_klass) for child in node.nodes]) if len(node.nodes) == 2: return self.pyjslib_name("op_bitor2", args=[ - self.expr(node.nodes[0], current_klass), + self.expr(node.nodes[0], current_klass), self.expr(node.nodes[1], current_klass)]) - return self.pyjslib_name("op_bitor", args="[%s]" % + return self.pyjslib_name("op_bitor", args="[%s]" % ", ".join([self.expr(child, current_klass) for child in node.nodes]) ) @@ -4028,8 +4028,8 @@ def _assattr(self, node, current_klass): attr_name = self.attrib_remap(node.attrname) lhs = self._lhsFromAttr(node, current_klass) if node.flags == "OP_DELETE": - self.w( self.spacing() + - self.pyjslib_name("delattr", + self.w( self.spacing() + + self.pyjslib_name("delattr", args="%s, '%s'" % (lhs, attr_name)) ) else: @@ -4057,10 +4057,10 @@ def _dict(self, node, current_klass): def _tuple(self, node, current_klass): return self.track_call("$p['tuple']([" + ", ".join([self.expr(x, current_klass) for x in node.nodes]) + "])", node.lineno) - + def _set(self, node, current_klass): - return self.track_call("$p['set']([" + ", ".join([self.expr(x, current_klass) for x in node.nodes]) + "])", node.lineno) - + return self.track_call("$p['set']([" + ", ".join([self.expr(x, current_klass) for x in node.nodes]) + "])", node.lineno) + def _sliceobj(self, node, current_klass): args = ", ".join([self.expr(x, current_klass) for x in node.nodes]) return self.track_call(self.pyjslib_name("slice", args=args), @@ -4111,12 +4111,12 @@ def _collcomp(self, node, current_klass): ], node.value) varinit = self.pyjslib_name("dict", args='') else: - raise TranslationError("unsupported collection comprehension", + raise TranslationError("unsupported collection comprehension", node, self.module_name) - + for qual in node.quals[::-1]: if len(qual.ifs) > 1: - raise TranslationError("unsupported ifs (in _collcomp)", + raise TranslationError("unsupported ifs (in _collcomp)", node, self.module_name) tassign = qual.assign tlist = qual.list @@ -4245,7 +4245,7 @@ def _if_expr(self, node, current_klass): return "(" + self.inline_bool_code(test) + "? (%(then)s) : (%(else_)s))" % locals() def _backquote(self, node, current_klass): - return self.pyjslib_name("repr", + return self.pyjslib_name("repr", args=self.expr(node.expr, current_klass)) def expr(self, node, current_klass): diff --git a/pyjs/src/pyjs/translator_proto.py b/pyjs/src/pyjs/translator_proto.py index 217ef6271..876c05f5b 100644 --- a/pyjs/src/pyjs/translator_proto.py +++ b/pyjs/src/pyjs/translator_proto.py @@ -26,7 +26,7 @@ import logging from options import (all_compile_options, add_compile_options, - get_compile_options, debug_options, speed_options, + get_compile_options, debug_options, speed_options, pythonic_options) if os.environ.has_key('PYJS_SYSPATH'): @@ -382,7 +382,7 @@ "tuple", "complex", "slice", - + "Ellipsis", # atom ] @@ -773,7 +773,7 @@ class Translator(object): 'noNumberClasses': [('number_classes', False)], 'NumberClasses': [('number_classes', True)], } - + pyjslib_prefix = "$p" def __init__(self, compiler, @@ -798,7 +798,7 @@ def __init__(self, compiler, self.output = output self.dynamic = dynamic self.findFile = findFile - + self.set_compile_options(kw) # compile options @@ -975,7 +975,7 @@ def __init__(self, compiler, self.w( '/*') self.w( 'PYJS_JS: %s' % repr(self.imported_js)) self.w( '*/') - + def set_compile_options(self, opts): opts = dict(all_compile_options, **opts) for opt, value in opts.iteritems(): @@ -983,7 +983,7 @@ def set_compile_options(self, opts): setattr(self, opt, value) else: raise Exception("Translator got an unknown option %s" % opt) - + self.ignore_debug = False self.inline_bool = self.inline_code self.inline_len = self.inline_code @@ -991,7 +991,7 @@ def set_compile_options(self, opts): self.inline_cmp = self.inline_code self.inline_getitem = self.inline_code if self.number_classes: - self.operator_funcs = True + self.operator_funcs = True def w(self, txt, newline=True, output=None, translate=True): if translate and txt: @@ -1107,7 +1107,7 @@ def add_callfunc(code, d, generic=True): self.pop_lookup() if code != '%s': - # XXX: Why is it here? It adds staticmethod to ANY decorated func, + # XXX: Why is it here? It adds staticmethod to ANY decorated func, # Even if its not method! code = code % ("@"+"{{staticmethod}}(%s)") if staticmethod: @@ -1167,7 +1167,7 @@ def jsname(self, name_type, jsname): if len(words) == 0: return words[0] # WTF FIXME TODO ????? return self.attrib_join(words) - + def pyjslib_name(self, name, args=None): if args is None: return "$p['" + name + "']" @@ -1365,7 +1365,7 @@ def inline_len_code(self, e): zero = "$constant_int_0" return self.__inline_len_code_str2 % locals() return "@{{len}}(%(e)s)" % locals() - + __inline_eq_code_str = """((%(v1)s=%(e1)s)===(%(v2)s=%(e2)s)&&%(v1)s===null?true: (%(v1)s===null?false:(%(v2)s===null?false: @@ -2078,8 +2078,8 @@ def _doImport(self, names, current_klass, root_level, assignBase, importName, context, self.modpfx()[:-1], - ) - + ) + if not assignBase: self.w( self.spacing() + import_stmt + ', null, false);') self._lhsFromName(importName, current_klass, modtype) @@ -2636,7 +2636,7 @@ def _tryExcept(self, node, current_klass): if expr.lineno: lineno = expr.lineno l = [] - + if isinstance(expr, self.ast.Tuple): for x in expr.nodes: l.append("((%s_name == %s.__name__)||@{{_isinstance}}(%s,%s))" % (pyjs_try_err, @@ -2708,7 +2708,7 @@ def _tryExcept(self, node, current_klass): self.stacksize_depth -= 1 self.generator_switch_case(increment=True) self.is_generator = save_is_generator - + def _with(self, v, current_klass): """ http://www.python.org/dev/peps/pep-0343/ @@ -2726,14 +2726,14 @@ def _with(self, v, current_klass): save_output = self.output self.output = StringIO() self.indent() - + for node in body_nodes: self._stmt(node, current_klass) - + self.dedent() captured_output = self.output self.output = save_output - + self.w(self.spacing() + "%(__with)s(%(expr)s, function(%(withvar)s){" % dict(expr=expr, __with=self.pyjslib_name('__with'), @@ -3346,16 +3346,16 @@ def _lhsFromAttr(self, v, current_klass): raise TranslationError( "unsupported type (in _assign)", v.expr, self.module_name) return lhs - - def _assigns_list(self, v, current_klass, expr): # DANIEL KLUEV VERSION + + def _assigns_list(self, v, current_klass, expr): # DANIEL KLUEV VERSION """ Handles all kinds of assignments for Assign, For and so on. - + expr is string representing expr to assign, i.e. self.expr() result - + Calls itself recursively for AssTuple - + Returns list of JS strings """ assigns = [] @@ -3371,7 +3371,7 @@ def _assigns_list(self, v, current_klass, expr): # DANIEL KLUEV VERSION desc_setattr = ("""%(l)s.__is_instance__ && """ """typeof %(l)s.__setattr__ == 'function' ? """ """%(l)s.__setattr__('%(a)s', %(r)s) : """ - """%(setattr)s(%(l)s, '%(a)s', %(r)s); """ % + """%(setattr)s(%(l)s, '%(a)s', %(r)s); """ % dict( setattr=self.pyjslib_name('setattr'), l=lhs, @@ -3412,7 +3412,7 @@ def _assigns_list(self, v, current_klass, expr): # DANIEL KLUEV VERSION upper = self.expr(v.upper, current_klass) obj = self.expr(v.expr, current_klass) assigns.append(self.track_call( - self.pyjslib_name("__setslice", + self.pyjslib_name("__setslice", args=[obj, lower, upper, expr]), v.lineno) + ';') return assigns @@ -3428,20 +3428,20 @@ def _assigns_list(self, v, current_klass, expr): # DANIEL KLUEV VERSION """ child_nodes = v.getChildNodes() extended_unpack = 'null' - - # Grammar and parser do not support extended unpack yet, + + # Grammar and parser do not support extended unpack yet, # should check each child and assign index if found extended flag for child in child_nodes: pass - + tempName = self.uniqid("$tupleassign") unpack_call = self.track_call( - self.pyjslib_name('__ass_unpack', + self.pyjslib_name('__ass_unpack', args=[expr, len(child_nodes), extended_unpack] ), v.lineno) - + assigns.append("var " + tempName + " = " + unpack_call + ";") - + for index,child in enumerate(child_nodes): unpacked_value = tempName + "[" + str(index) + "]"; assigns.extend(self._assigns_list(child, current_klass, unpacked_value)) @@ -3452,7 +3452,7 @@ def _assigns_list(self, v, current_klass, expr): # DANIEL KLUEV VERSION assigns.append(lhs + " "+ op + " " + expr + ";") return assigns - def _assign(self, node, current_klass): # DANIEL KLUEV VERSION + def _assign(self, node, current_klass): # DANIEL KLUEV VERSION if len(node.nodes) != 1: tempvar = self.uniqid("$assign") tnode = self.ast.Assign([self.ast.AssName(tempvar, "OP_ASSIGN", node.lineno)], node.expr, node.lineno) @@ -3498,8 +3498,8 @@ def _discard(self, node, current_klass): # Kluev version # XXX: should trigger exceptions if expr resolves to undefined expr = self.expr(node.expr, current_klass) self.w(self.spacing() + expr + ";") - - + + def _if(self, node, current_klass): save_is_generator = self.is_generator if self.is_generator: @@ -3691,7 +3691,7 @@ def _for(self, node, current_klass): # DANIEL KLUEV VERSION else: assTestvar = "" reuse_tuple = "false" - + if self.inline_code: rhs = nextval else: @@ -3744,7 +3744,7 @@ def _for(self, node, current_klass): # DANIEL KLUEV VERSION self.generator_add_state() self.generator_switch_open() self.generator_switch_case(increment=False) - + for line in assigns: self.w( self.spacing() + line) @@ -3811,7 +3811,7 @@ def _while(self, node, current_klass): self.w( self.dedent() + "}") self.generator_switch_case(increment=True) self.is_generator = save_is_generator - + def _const(self, node): if isinstance(node.value, int): @@ -3960,7 +3960,7 @@ def _mod(self, node, current_klass): return """((%(v1)s=%(e1)s)!=null && (%(v2)s=%(e2)s)!=null && typeof %(v1)s=='string'? %(s)s\t@{{sprintf}}(%(v1)s,%(v2)s): %(s)s\t((%(v1)s=%(v1)s%%%(v2)s)<0&&%(v2)s>0?%(v1)s+%(v2)s:%(v1)s))""" % locals() - + return """(typeof (%(v1)s=%(e1)s)==typeof (%(v2)s=%(e2)s) && typeof %(v1)s=='number'? %(s)s\t((%(v1)s=%(v1)s%%%(v2)s)<0&&%(v2)s>0?%(v1)s+%(v2)s:%(v1)s): %(s)s\t@{{op_mod}}(%(v1)s,%(v2)s))""" % locals() @@ -4067,10 +4067,10 @@ def _dict(self, node, current_klass): def _tuple(self, node, current_klass): return self.track_call("$p['tuple']([" + ", ".join([self.expr(x, current_klass) for x in node.nodes]) + "])", node.lineno) - + def _set(self, node, current_klass): - return self.track_call("$p['set']([" + ", ".join([self.expr(x, current_klass) for x in node.nodes]) + "])", node.lineno) - + return self.track_call("$p['set']([" + ", ".join([self.expr(x, current_klass) for x in node.nodes]) + "])", node.lineno) + def _sliceobj(self, node, current_klass): args = ", ".join([self.expr(x, current_klass) for x in node.nodes]) return self.track_call(self.pyjslib_name("slice", args=args), @@ -4123,12 +4123,12 @@ def _collcomp(self, node, current_klass): # DANIEL KLUEV VERSION - meant to repl ], node.value) varinit = self.pyjslib_name("dict", args='') else: - raise TranslationError("unsupported collection comprehension", + raise TranslationError("unsupported collection comprehension", node, self.module_name) - + for qual in node.quals[::-1]: if len(qual.ifs) > 1: - raise TranslationError("unsupported ifs (in _collcomp)", + raise TranslationError("unsupported ifs (in _collcomp)", node, self.module_name) tassign = qual.assign tlist = qual.list diff --git a/pyjs/tests/test-coverage.py b/pyjs/tests/test-coverage.py index 25af285fd..7c64c55a9 100644 --- a/pyjs/tests/test-coverage.py +++ b/pyjs/tests/test-coverage.py @@ -23,7 +23,7 @@ def stop(self): sys.settrace(None) def output(self, *files): - + print """ <html> <head> @@ -67,11 +67,11 @@ def output(self, *files): </head> <body> """ % self.testset_name - + print """ <h1>Coverage for %s</h1> """ % self.testset_name - + for filename in files: print """ <h2>%s</h2> @@ -94,11 +94,11 @@ def output(self, *files): print """ </table> """ - + print """ </body> </html> - """ + """ # Tester diff --git a/pyjs/tests/test-report.py b/pyjs/tests/test-report.py index 8cccebd0d..2a5fe1fd9 100644 --- a/pyjs/tests/test-report.py +++ b/pyjs/tests/test-report.py @@ -26,7 +26,7 @@ def stop(self): sys.settrace(None) def output(self, *files): - + print """ <html> <head> @@ -70,11 +70,11 @@ def output(self, *files): </head> <body> """ % self.testset_name - + print """ <h1>Coverage for %s</h1> """ % self.testset_name - + for filename in files: print """ <h2>%s</h2> @@ -97,11 +97,11 @@ def output(self, *files): print """ </table> """ - + print """ </body> </html> - """ + """ print """ @@ -129,10 +129,10 @@ def test(filename, module): if output == desired_output: print "<p>pass</p>" else: - print differ.make_table(output.split("\n"), desired_output.split("\n"), context=True) + print differ.make_table(output.split("\n"), desired_output.split("\n"), context=True) except Exception, e: print "\texception", e - + import sys sys.path.append("..") diff --git a/pyjs/tests/test006.py b/pyjs/tests/test006.py index fc4f8b87b..fc2bddd04 100644 --- a/pyjs/tests/test006.py +++ b/pyjs/tests/test006.py @@ -31,7 +31,7 @@ def __init__(self, element): def setHTML(self, html): DOM.setInnerHTML(self.getElement(), html) - + class Button(ButtonBase): diff --git a/pyjs/tests/test007.py b/pyjs/tests/test007.py index b98a33702..46e376ae9 100644 --- a/pyjs/tests/test007.py +++ b/pyjs/tests/test007.py @@ -26,7 +26,7 @@ class ComplexPanel(Panel): def __init__(self): self.children = [] - + def add(self, widget): self.children.append(widget) widget.setParent(self) diff --git a/pyjs/tests/test008.py b/pyjs/tests/test008.py index d994e4ffe..816d419d1 100644 --- a/pyjs/tests/test008.py +++ b/pyjs/tests/test008.py @@ -26,7 +26,7 @@ class ComplexPanel(Panel): def __init__(self): self.children = [] - + def add(self, widget): self.children.append(widget) widget.setParent(self) @@ -39,7 +39,7 @@ def __init__(self): ComplexPanel.__init__(self) self.setElement(DOM.createDiv()) DOM.setStyleAttribute(self.getElement(), "overflow", "hidden") - + def add(self, widget): ComplexPanel.add(self, widget) DOM.appendChild(self.getElement(), widget.getElement()) diff --git a/pyjs/tests/test009.py b/pyjs/tests/test009.py index b5c2ebccc..386a3fe9b 100644 --- a/pyjs/tests/test009.py +++ b/pyjs/tests/test009.py @@ -26,7 +26,7 @@ class ComplexPanel(Panel): def __init__(self): self.children = [] - + def add(self, widget): self.children.append(widget) widget.setParent(self) @@ -39,7 +39,7 @@ def __init__(self): ComplexPanel.__init__(self) self.setElement(DOM.createDiv()) DOM.setStyleAttribute(self.getElement(), "overflow", "hidden") - + def add(self, widget): ComplexPanel.add(self, widget) DOM.appendChild(self.getElement(), widget.getElement()) @@ -48,7 +48,7 @@ def add(self, widget): class RootPanel(AbsolutePanel): - + def __init__(self): AbsolutePanel.__init__(self) element = self.getBodyElement() diff --git a/pyjs/tests/test012.py b/pyjs/tests/test012.py index 90c601539..07e92a5a5 100644 --- a/pyjs/tests/test012.py +++ b/pyjs/tests/test012.py @@ -17,7 +17,7 @@ def onAttach(self): return self.attached = True DOM.setEventListener(self.getElement(), self) - + def onDetach(self): if not self.attached: return diff --git a/pyjs/tests/test015.py b/pyjs/tests/test015.py index 74e3c0122..d7ff1c1b6 100644 --- a/pyjs/tests/test015.py +++ b/pyjs/tests/test015.py @@ -4,7 +4,7 @@ def __init__(self, dayOfWeek, startMinutes, endMinutes): self.dayOfWeek = dayOfWeek self.startMinutes = startMinutes self.endMinutes = endMinutes - + def compareTo(self, other): if self.dayOfWeek < other.dayOfWeek: return -1 diff --git a/pyjs/tests/test019.py b/pyjs/tests/test019.py index 0e495101f..359b8d7bd 100644 --- a/pyjs/tests/test019.py +++ b/pyjs/tests/test019.py @@ -5,7 +5,7 @@ def __init__(self): def addTimeSlot(self, timeSlot): self.timeSlots.append(timeSlot) - + def getDescription(self, daysFilter): s = None for timeSlot in self.timeSlots: diff --git a/pyjs/tests/test027.py b/pyjs/tests/test027.py index a104d2b0e..ffa7fd682 100644 --- a/pyjs/tests/test027.py +++ b/pyjs/tests/test027.py @@ -4,7 +4,7 @@ def accept(self, startRow, data): srcRowIndex = 0 srcRowCount = 5 destRowIndex = 1 - + while srcRowIndex < srcRowCount: srcRowIndex += 1 destRowIndex += 1 diff --git a/pyjs/tests/test028.py b/pyjs/tests/test028.py index 421ab127c..c22b6b5ce 100644 --- a/pyjs/tests/test028.py +++ b/pyjs/tests/test028.py @@ -3,35 +3,35 @@ class RowDataAcceptorImpl: def accept(self, startRow, data): destRowCount = getDataRowCount() destColCount = grid.getCellCount(0) - + srcRowIndex = 0 srcRowCount = 5 destRowIndex = 1 - + while srcRowIndex < srcRowCount: - + srcRowData = data[srcRowIndex] - + for srcColIndex in range(destColCount): cellHTML = srcRowData[srcColIndex] grid.setText(destRowIndex, srcColIndex, cellHTML) - + srcRowIndex += 1 destRowIndex += 1 - + isLastPage = False - + while destRowIndex < destRowCount + 1: - + isLastPage = True - + for destColIndex in range(destColCount): grid.clearCell(destRowIndex, destColIndex) - + destRowIndex += 1 - + navbar.gotoNet.setEnabled(not isLstPage) navbar.gotoFirst.setEnabled(startRow > 0) navbar.gotoPrev.setEnabled(startRow > 0) - + setStatusText((startRow + 1) + " - " + (startRow + srcRowCount)) diff --git a/pyjs/tests/test029.py b/pyjs/tests/test029.py index 9b7d0bf2b..8be918221 100644 --- a/pyjs/tests/test029.py +++ b/pyjs/tests/test029.py @@ -1,5 +1,5 @@ class DynaTableWidget: - + def initTable(self, columns, columnStyles, rowCount): self.grid.resize(rowCount + 1, len(columns)) for i in range(len(columns)): diff --git a/pyjs/tests/test031.py b/pyjs/tests/test031.py index df6e602e5..494fa2e64 100644 --- a/pyjs/tests/test031.py +++ b/pyjs/tests/test031.py @@ -1,6 +1,6 @@ class Foo: BAR = 1 BAZ = 2 - + def test(): return Foo.BAR \ No newline at end of file diff --git a/pyjs/tests/test040.py b/pyjs/tests/test040.py index 2fd0a76bf..4dcab42e0 100644 --- a/pyjs/tests/test040.py +++ b/pyjs/tests/test040.py @@ -12,7 +12,7 @@ def test(self): self.foo = 5 biz.baz.foo = 5 baz[2].foo = 5 - + # augmented assignments foo += 5 bar.foo += 5 diff --git a/pysm/pysmrun.py b/pysm/pysmrun.py index 4eeb5c14c..fdee15947 100644 --- a/pysm/pysmrun.py +++ b/pysm/pysmrun.py @@ -117,8 +117,8 @@ def main(): txt = template % {'app_libs': app_libs, 'module_name': file_name, 'module': txt} - txt += "sys();\n" - txt += "pyjslib();\n" + txt += "sys();\n" + txt += "pyjslib();\n" txt += "%s();\n" % file_name if options.output: diff --git a/pyv8/depstest.py b/pyv8/depstest.py index acdca6dcd..8261abab0 100644 --- a/pyv8/depstest.py +++ b/pyv8/depstest.py @@ -35,10 +35,10 @@ def __init__(self, name, file, deps, mods): self.result = False self.error = '' self.source = '' - + def __repr__(self): return "<module '{0.name}' from '{0.file}'>".format(self) - + def paint(self, dist=0, parent=None): if parent and not parent.name in self.rdeps: self.rdeps.append(parent.name) @@ -47,11 +47,11 @@ def paint(self, dist=0, parent=None): for dep in self.deps: if not dep in self.rdeps: self.mods[dep].paint(self.distance + 1, self) - + def export(self): return ("{0.name}\t{0.file}\t{0.distance}\t" "{0.deps}\t{0.rdeps}\t{0.result}\t{0.error!r}\n".format(self)) - + def export_json(self): return dict(name=self.name, file=self.file, @@ -61,8 +61,8 @@ def export_json(self): source=self.source, error=self.error, result=self.result) - - + + def set_result(self, r): err = '' if isinstance(r, JSRuntimeError): @@ -75,7 +75,7 @@ def set_result(self, r): t = r self.result = t self.error = err - + def set_source(self, stdlib_sources): if self.file.startswith('stdlib'): if self.name in stdlib_sources: @@ -86,7 +86,7 @@ def set_source(self, stdlib_sources): self.source = 'pyjs' else: self.source = 'other' - + def __cmp__(self, a): return self.distance.__cmp__(a.distance) @@ -106,7 +106,7 @@ def main(): mod = basename(mod) if '.' in mod: mod = mod.split('.')[0] - + translator_arguments = translator.get_compile_options(options) out = mkdtemp(prefix='pyjs_depstest') compiler = translator.compiler @@ -117,13 +117,13 @@ def main(): path=pyjs.path, compiler=translator.compiler, translator_arguments=translator_arguments) - linker() - + linker() + mod_src = dict(map( lambda x: x.strip().split(':'), open(join(pyjs.pyjspth, 'stdlib', 'modules_sources')).readlines()) ) - + mods = {} mods[mod] = Module(mod, args[0], linker._file_deps[None], mods) for fn, mn in linker._file_to_module.iteritems(): @@ -131,14 +131,14 @@ def main(): mods[mn].set_source(mod_src) if not 'pyjslib' in mods[mod].deps: mods[mod].deps.append('pyjslib') - + mods[mod].paint() nf2 = defaultdict(set) for nf, rdeps in linker._not_found.iteritems(): if not nf.split('.')[0] in mods: nf2[nf.split('.')[0]].update( map(lambda x: linker._file_to_module[x], rdeps)) - + for nf, rdeps in nf2.iteritems(): print "Not found {} depended by {}".format(nf, list(rdeps)) for m in mods: @@ -148,13 +148,13 @@ def main(): compiler=translator.compiler, translator_arguments=translator_arguments) mods[m].set_result(test_dependency(linker)) - + outf = open('{}.deps'.format(mod), 'w') for m in sorted(mods.values()): outf.write(m.export()) outf.close() print "Exported dependency tree to {}.deps".format(mod) - + outf = open('{}.deps.json'.format(mod), 'w') outf.write(DepsJSON().encode(mods.values())) outf.close() @@ -172,7 +172,7 @@ def test_dependency(linker): fp.close() except Exception, e: return e - + try: ctxt.enter() x = ctxt.eval(txt) @@ -180,7 +180,7 @@ def test_dependency(linker): res = JSRuntimeError(ctxt, e) finally: if ctxt.entered: - ctxt.leave() + ctxt.leave() return res _deps_cache = {} @@ -189,19 +189,19 @@ class DepsTestLinker(PyV8Linker): def __init__(self, *args, **kw): PyV8Linker.__init__(self, *args, **kw) self.translator_func = self._translator_func - + def _translator_func(self, platform, file_names, out_file, module_name, translator_args, incremental): if out_file in _deps_cache: return _deps_cache[out_file] - + deps, js_libs = translate(self.compiler, file_names, out_file, module_name, **translator_args) _deps_cache[out_file] = (deps, js_libs) - return deps, js_libs + return deps, js_libs class DepsExport(PyV8Linker): def __init__(self, *args, **kw): @@ -210,7 +210,7 @@ def __init__(self, *args, **kw): self._file_to_module = {} self._file_deps = defaultdict(set) self._not_found = defaultdict(set) - + def _translator_func(self, platform, file_names, out_file, module_name, translator_args, incremental): kw = dict(self.translator_arguments) @@ -221,7 +221,7 @@ def _translator_func(self, platform, file_names, out_file, module_name, module_name, **kw) return deps, js_libs - + def visit_modules(self, module_names, platform=None, parent_file = None): prefix = '' all_names = [] @@ -270,7 +270,7 @@ def visit_modules(self, module_names, platform=None, parent_file = None): self._file_to_module[p] = mn self._file_deps[parent_file].add(mn) self.visit_module(p, override_paths, platform, module_name=mn) - + if __name__ == '__main__': main() diff --git a/pyv8/jsglobal.py b/pyv8/jsglobal.py index d3bf552bd..8981afa55 100644 --- a/pyv8/jsglobal.py +++ b/pyv8/jsglobal.py @@ -25,38 +25,38 @@ def read(self, bytes=None): class Global(PyV8.JSClass): def __init__(self, argv=None, path=None): PyV8.JSClass.__init__(self) - + if argv is None: self.argv = sys.argv else: self.argv = argv - + if path is None: self.path = sys.path else: self.path = path - + # Funcs to initialize sys def pyv8_sys_get_stdin(self): return sys.stdin - + def pyv8_sys_get_stdout(self): return sys.stdout - + def pyv8_sys_get_stderr(self): return sys.stderr - + def pyv8_sys_get_argv(self): return self.argv[:] - + def pyv8_sys_get_path(self): return self.path[:] - + def pyv8_open(self, fname, mode): return FileWrapper(fname, mode) - - + + def pyv8_import_module(self, parent_name, module_name): #print "pyv8_import_module", parent_name, module_name diff --git a/pyv8/linker.py b/pyv8/linker.py index f13fc3fed..060d5c079 100644 --- a/pyv8/linker.py +++ b/pyv8/linker.py @@ -84,7 +84,7 @@ def __init__(self, *args, **kwargs): kwargs['platforms'] = [PLATFORM] super(PyV8Linker, self).__init__(*args, **kwargs) self.translator_func = self._translator_func - + def _translator_func(self, platform, file_names, out_file, module_name, translator_args, incremental): cached = False @@ -102,10 +102,10 @@ def _translator_func(self, platform, file_names, out_file, module_name, if cached: deps, js_libs = linker.parse_outfile(out_file) return deps, js_libs - deps, js_libs = linker.out_translate(platform, file_names, out_file, + deps, js_libs = linker.out_translate(platform, file_names, out_file, module_name, translator_args, incremental) - return deps, js_libs + return deps, js_libs def visit_start(self): super(PyV8Linker, self).visit_start() @@ -170,5 +170,5 @@ def static_code(libs, msg = None): out_file = open(self.out_file_mod , 'w') out_file.write(APP_TEMPLATE % locals()) out_file.close() - + add_linker_options = linker.add_linker_options \ No newline at end of file diff --git a/pyv8/pyv8run.py b/pyv8/pyv8run.py index 1d4c279c7..87da2231b 100644 --- a/pyv8/pyv8run.py +++ b/pyv8/pyv8run.py @@ -30,7 +30,7 @@ class JSRuntimeError(Exception): def __init__(self, ctxt, exc): - self.module = ctxt.locals['$pyjs']['track']['module'] + self.module = ctxt.locals['$pyjs']['track']['module'] self.lineno = ctxt.locals['$pyjs']['track']['lineno'] self.traceback = self.get_traceback(ctxt.locals['$pyjs']['trackstack']) if ':' in exc.message and not ' ' in exc.message.split(':', 1)[0]: @@ -40,22 +40,22 @@ def __init__(self, ctxt, exc): else: self.jserrortype = exc.__class__.__name__ self.jserrortext = exc.message - + def __str__(self): return "{0.jserrortype}: {0.module}.py:{0.lineno} {0.jserrortext}".\ format(self) - + def full(self): return ("{0.jserrortype}: {0.module}.py:{0.lineno}\n" "Traceback:\n{trace}\n" "{0.jserrortext}".format(self, trace=self.get_traceback_text())) - + def get_traceback(self, jstb): tb = [] for x in jstb: tb.append(dict(module=x['module'], lineno=x['lineno'])) return tb - + def get_traceback_text(self): trace = [] for x in self.traceback: @@ -80,7 +80,7 @@ def main(): "-c", dest="command", help="Python command to run") - + args = sys.argv[1:] app_args = [] if '--' in args: @@ -97,9 +97,9 @@ def main(): modules = ['main'] else: modules = args - + app_args[0:0] = [modules[0]] - + _modules = [] for mod in modules: if mod.startswith('.') or mod.startswith('/') or mod.endswith('.py'): @@ -108,10 +108,10 @@ def main(): else: _modules.append(mod) modules = _modules - + pyjs.path[0:0] = [join(pyjs.pyjspth, 'stdlib')] pyjs.path.append(join(pyjs.pyjspth, 'pyjs', 'src')) - + for d in options.library_dirs: pyjs.path.append(os.path.abspath(d)) @@ -123,13 +123,13 @@ def main(): compiler=translator.compiler, translator_arguments=translator_arguments) linker() - + fp = open(linker.out_file_mod, 'r') txt = fp.read() fp.close() #PyV8.debugger.enabled = True - + # create a context with an explicit global g = Global(app_args, pyjs.path) ctxt = PyV8.JSContext(g) @@ -140,7 +140,7 @@ def main(): x = ctxt.eval(txt) except Exception, e: print JSRuntimeError(ctxt, e).full() - + if IS_REPL: from repl import REPL REPL(translator.compiler, linker, translator_arguments, g, ctxt)() diff --git a/pyv8/repl.py b/pyv8/repl.py index 90635aa45..7f7e76306 100644 --- a/pyv8/repl.py +++ b/pyv8/repl.py @@ -16,7 +16,7 @@ def __init__(self, compiler, linker, translator_arguments, self.jscontext = jscontext self.jscontext.eval(js_interactive_func) self.jscontext.eval(set_main) - + def __call__(self): """ Start read-eval-print loop @@ -31,7 +31,7 @@ def __call__(self): jsglob = self.jsglobal ) self.shell(local_ns=locs) - + def translate(self, src): output = StringIO() tree = self.compiler.parse(src + "\n") @@ -41,7 +41,7 @@ def translate(self, src): jssrc = output.getvalue() output.close() return jssrc, t.imported_modules, t.imported_js - + def eval(self, code, print_result=False): try: res = self.jscontext.eval(code) @@ -50,7 +50,7 @@ def eval(self, code, print_result=False): except Exception, e: print e return 0 - + js_interactive_func = """ function runinteractive (f, ctxt) { @@ -74,7 +74,7 @@ def eval(self, code, print_result=False): jsctxt - PyV8 context jsglob - PyV8 globals """ - + class V8InteractiveShell(InteractiveShell): _js_int = None _is_native = False @@ -201,7 +201,7 @@ def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None, mode = self.IP.rc.xmode, call_pdb = self.IP.rc.pdb) self.restore_system_completer() - + class InteractiveTranslator(translator.Translator): def __init__(self, compiler, @@ -224,11 +224,11 @@ def __init__(self, compiler, self.output = output self.dynamic = dynamic self.findFile = findFile - + self.set_compile_options(kw) self.future_division = False - + self.imported_modules = [] self.imported_js = [] self.is_class_definition = False diff --git a/run_bootstrap_first_then_setup.py b/run_bootstrap_first_then_setup.py index 222910dad..1976f4332 100755 --- a/run_bootstrap_first_then_setup.py +++ b/run_bootstrap_first_then_setup.py @@ -42,7 +42,7 @@ def get_files(d): if fname == "PureMVC_Python_1_0": continue if fname[-4:] == ".pyc": # ehmm.. no. - continue + continue if os.path.isdir(p): get_dir(p) else: diff --git a/test.py b/test.py index 7562d8628..39e59f051 100755 --- a/test.py +++ b/test.py @@ -1,6 +1,6 @@ #!/usr/bin/env python """ -Utility to run all possible tests and provide overall results. +Utility to run all possible tests and provide overall results. Test plan: @@ -123,7 +123,7 @@ class PyjamasTester(object): dest="examples_run", action="store_true", help="Test examples" - ) + ) parser.add_option( "--examples-path", dest="examples_path", @@ -138,52 +138,52 @@ class PyjamasTester(object): default=False, help="Provide report on tracker issues lacking failing tests" ) - + def __init__(self): self.options, args = self.parser.parse_args() - + self.tmpdir = mkdtemp(prefix='pyjs') self.root = path.dirname(__file__) - + print "Output will be produced in %s" % self.tmpdir - + self.tracker_url = "http://code.google.com/p/pyjamas/issues/csv" if not path.isabs(self.options.pyv8): self.options.pyv8 = path.join(currentdir, self.options.pyv8) if self.options.pyv8.endswith(".py"): self.options.pyv8 = "%s %s" % (self.options.cpython, self.options.pyv8) - + if not path.isabs(self.options.examples_path): self.options.examples_path = path.join(currentdir, self.options.examples_path) - + self.testsresults = [] self.testsknown = [] - + if self.options.libtest_only: self.options.utils_run = False self.options.examples_run = False - + if self.options.libtest_run: self._test(self.test_libtest_cpython) if self.options.libtest_run: if self.options.pyv8_run: self._test(self.test_libtest_pyv8) - + if self.options.utils_run: self._test(self.test_pyjsbuild) self._test(self.test_pyjscompile) self._test(self.test_pyjampiler) - + if self.options.examples_run: self._test(self.test_examples) - + self.issues = {} if self.options.tracker: self.get_tracker_issues() - + self.print_results() - + def run_cmd(self, cmd=None, opts=None, cwd=None): @@ -220,21 +220,21 @@ def test_libtest_pyv8(self, output): example_files = [path.join("I18N", basename) for basename in example_files] return self.parse_cmd_output( *self.run_cmd(cmd=self.options.pyv8, - opts=["-o %s" % output, - "--strict", + opts=["-o %s" % output, + "--strict", "--dynamic '^I18N[.].*.._..'", "LibTest"] + example_files, cwd=directory) ) - + def test_examples(self, output): return self.check_stderr(*self.run_cmd( - opts=["__main__.py", + opts=["__main__.py", "--download", # should it be there or not ??? - "--", + "--", "-o %s" % output,], cwd=self.options.examples_path)) - + def test_pyjsbuild(self, output): return self.check_stderr(*(self.run_cmd( path.join(self.root, 'bin', 'pyjsbuild'), @@ -244,7 +244,7 @@ def test_pyjsbuild(self, output): ], cwd=path.join(self.options.examples_path, 'libtest')) + ('libtest', 'compile'))) - + def test_pyjscompile(self, output): return self.check_stderr(*(self.run_cmd( path.join(self.root, 'bin', 'pyjscompile'), @@ -254,7 +254,7 @@ def test_pyjscompile(self, output): ], cwd=path.join(self.options.examples_path, 'libtest')) + ('libtest', 'compile'))) - + def test_pyjampiler(self, output): cmd = path.join(self.root, 'bin', 'pyjampiler') r = self.check_stderr(*(self.run_cmd( @@ -273,7 +273,7 @@ def test_pyjampiler(self, output): cwd=path.join(self.options.examples_path, 'libtest')) + ('libtest', 'compile'))) return r - + def check_stderr(self, stdout, stderr, cls='cmd', name=''): if not name: name = cls @@ -294,12 +294,12 @@ def check_stderr(self, stdout, stderr, cls='cmd', name=''): return [dict(cls = cls, status = "passed", name = name, - count = 1)] - + count = 1)] + def parse_cmd_output(self, stdout_value, stderr_value=None): """ Parse stdout/stderr into list of dicts - + """ res = [] for line in stdout_value.split('\n'): @@ -334,12 +334,12 @@ def parse_cmd_output(self, stdout_value, stderr_value=None): message = stderr_value )) return res - - - + + + def _test(self, method): name = method.im_func.func_name - d = dict(name=name, + d = dict(name=name, tests=[], failed_list=[], known_list=[], total=0, passed=0, failed=0, known=0, err=None) @@ -353,7 +353,7 @@ def _test(self, method): print e d['err'] = e return False - + for test in d['tests']: if test['status'] == 'passed': d['passed'] += test['count'] @@ -365,7 +365,7 @@ def _test(self, method): d['known_list'].append(test) self.testsknown.append((d, test)) d['total'] = d['passed'] + d['failed'] + d['known'] - + def get_tracker_issues(self): print "Fetching issues csv from %s" % self.tracker_url csv_data = urllib2.urlopen(self.tracker_url) @@ -378,7 +378,7 @@ def get_tracker_issues(self): issue = issue_cls(*row) self.issues[issue.ID] = issue print " received %s issues from tracker" % len(self.issues) - + def print_results(self): """ .. TODO:: handle test_pack['err'] @@ -392,7 +392,7 @@ def print_results(self): for test_pack in self.testsresults: print "-"*30 print ("%(name)s: total %(total)s, passed %(passed)s," - " known %(known)s, failed %(failed)s" % test_pack) + " known %(known)s, failed %(failed)s" % test_pack) print "-"*30 if test_pack['failed'] > 0: is_failed = True @@ -412,7 +412,7 @@ def print_results(self): print test_pack['name'], "failed tests:" for test in test_pack['failed_list']: print "[!] %(cls)s.%(name)s: %(message)s" % test - + if self.issues: referenced = [] for test_pack, test in self.testsknown: @@ -428,7 +428,7 @@ def print_results(self): test_pack['name'], test['cls'], test['name'], test['message']) - + if self.options.tracker_report: print "="*30 print " Issues test coverage report" @@ -436,11 +436,11 @@ def print_results(self): for issue_id, issue in self.issues.iteritems(): if not issue_id in referenced: print " No test for issue #%(ID)s '%(Summary)s'" % issue._asdict() - - - + + + if __name__ == '__main__': PyjamasTester()