Statistics
| Revision:

gvsig-scripting / org.gvsig.scripting / trunk / org.gvsig.scripting / org.gvsig.scripting.app / org.gvsig.scripting.app.mainplugin / src / main / resources-plugin / scripting / lib / gvsig / libs / formpanel.py @ 855

History | View | Annotate | Download (13.9 KB)

1

    
2
import com.jeta.forms.components.panel.FormPanel
3

    
4
import java.lang.Runnable
5
import java.io.FileInputStream
6
import java.io.File
7
import java.awt.event.ActionListener
8
import java.awt.event.MouseListener
9
import java.awt.event.ItemListener
10
import javax.imageio.ImageIO
11
import javax.swing.AbstractButton
12
import javax.swing.JButton
13
import javax.swing.JComboBox
14
import javax.swing.JList
15
import javax.swing.JRadioButton
16
import javax.swing.JSpinner
17
import javax.swing.SwingUtilities
18
import javax.swing.ImageIcon
19
import javax.swing.text.JTextComponent
20
import javax.swing.Timer
21
import javax.swing.event.ChangeListener
22
import javax.swing.event.DocumentListener
23
import javax.swing.event.ListSelectionListener
24

    
25
import os
26
import os.path
27
import threading
28

    
29
import inspect
30

    
31
from gvsig import getResource
32

    
33
from org.gvsig.tools.swing.api import ToolsSwingLocator
34
from org.gvsig.tools.task import TaskStatus
35
from org.gvsig.tools.observer import Observer
36
from org.gvsig.tools import ToolsLocator
37
import org.gvsig.tools.swing.api.Component
38

    
39
from com.jeta.open.registry import JETARegistry
40
from com.jeta.open.resources import ResourceLoader
41
from org.gvsig.scripting import ScriptingLocator
42
from java.net import URL
43
from java.net import URLClassLoader
44
from jarray import array
45

    
46
class ListenerAdapter(object):
47
  def __init__(self,function,componentName=None):
48
    self.function = function
49
    self.synchronous  = True
50
    if componentName == None:
51
      self.componentName = self.function.__name__
52
    else:
53
      self.componentName = componentName
54
    x = getattr(function,"im_func",function)
55
    x.setSynchronous = self.setSynchronous
56
  def setSynchronous(self, value):
57
    self.synchronous = value
58
  def __call__(self, *args):
59
    if self.synchronous:
60
      self.function(*args)
61
    else:
62
      threading.Thread(target=self.function, name=self.componentName, args=args).start()
63

    
64
#----------------
65
# Falla invocar a ListenerAdapter.__init__(self,function,componentName)
66
# por que dice que self no es un ListenerAdapter.
67
# De momento duplico el codigo de ListenerAdapter incrustandolo en esta clase.
68
class ActionListenerAdapter_Upss(ListenerAdapter, java.awt.event.ActionListener):
69
  def __init__(self,function,componentName=None):
70
    ListenerAdapter.__init__(self,function,componentName)
71
  def actionPerformed(self,*args):
72
    #print "ActionListenerAdapter %s %s" % (self.componentName, args[0])
73
    self(*args)
74

    
75
class ActionListenerAdapter(java.awt.event.ActionListener):
76
  def __init__(self,function,componentName=None):
77
    self.function = function
78
    self.synchronous  = True
79
    if componentName == None:
80
      self.componentName = self.function.__name__
81
    else:
82
      self.componentName = componentName
83
    x = getattr(function,"im_func",function)
84
    x.setSynchronous = self.setSynchronous
85
  def setSynchronous(self, value):
86
    self.synchronous = value
87
  def __call__(self, *args):
88
    if self.synchronous:
89
      self.function(*args)
90
    else:
91
      threading.Thread(target=self.function, name=self.componentName, args=args).start()
92

    
93
  def actionPerformed(self,*args):
94
    #print "ActionListenerAdapter %s %s" % (self.componentName, args[0])
95
    self(*args)
96

    
97

    
98
class ChangeListenerAdapter(ListenerAdapter, javax.swing.event.ChangeListener):
99
  def __init__(self,function, componentName=None):
100
    ListenerAdapter.__init__(self,function,componentName)
101
  def stateChanged(self,*args):
102
    #print "ChangeListenerAdapter %s %s" % (self.componentName, args[0])
103
    self(*args)
104

    
105
class DocumentListenerAdapter(ListenerAdapter, javax.swing.event.DocumentListener):
106
  def __init__(self,function, componentName=None):
107
    ListenerAdapter.__init__(self,function,componentName)
108
  def insertUpdate(self,*args):
109
    #print "DocumentListenerAdapter %s" % self.componentName
110
    self.function(*args)
111
  def removeUpdate(self,*args):
112
    #print "DocumentListenerAdapter %s" % self.componentName
113
    self(*args)
114
  def changedUpdate(self,*args):
115
    #print "DocumentListenerAdapter %s" % self.componentName
116
    self(*args)
117

    
118
class ItemListenerAdapter(ListenerAdapter, java.awt.event.ItemListener):
119
  def __init__(self,function, componentName=None):
120
    ListenerAdapter.__init__(self,function,componentName)
121
  def itemStateChanged(self,*args):
122
    #print "ItemListenerAdapter %s %s" % (self.componentName, args[0])
123
    self(*args)
124

    
125
class ListSelectionListenerAdapter(ListenerAdapter, javax.swing.event.ListSelectionListener):
126
  def __init__(self,function, componentName=None):
127
    ListenerAdapter.__init__(self,function,componentName)
128
  def valueChanged(self,*args):
129
    #print "ListSelectionListenerAdapter %s %s" % (self.componentName, args[0])
130
    self(*args)
131

    
132
class FocusGainedListenerAdapter(ListenerAdapter, java.awt.event.FocusListener):
133
  def __init__(self,function, componentName=None):
134
    ListenerAdapter.__init__(self,function,componentName)
135
  def focusGained(self,*args):
136
    #print "focusGained %s %s" % (self.componentName, args[0])
137
    self(*args)
138
  def focusLost(self,*args):
139
    #print "focusLost %s %s" % (self.componentName, args[0])
140
    pass
141

    
142
class FocusLostListenerAdapter(ListenerAdapter, java.awt.event.FocusListener):
143
  def __init__(self,function, componentName=None):
144
    ListenerAdapter.__init__(self,function,componentName)
145
  def focusGained(self,*args):
146
    pass
147
  def focusLost(self,*args):
148
    self(*args)
149

    
150
class MouseListenerAdapter(ListenerAdapter, java.awt.event.MouseListener):
151
  def __init__(self,function, componentName=None):
152
    ListenerAdapter.__init__(self,function,componentName)
153
  def mouseClicked(self,*args):
154
    self(*args)
155
  def mouseEntered(self,*args):
156
    self(*args)
157
  def mouseExited(self,*args):
158
    self(*args)
159
  def mousePressed(self,*args):
160
    self(*args)
161
  def mouseReleased(self,*args):
162
    self(*args)
163

    
164
class KeyPressedListenerAdapter(ListenerAdapter, java.awt.event.KeyListener):
165
  def __init__(self,function, componentName=None):
166
    ListenerAdapter.__init__(self,function,componentName)
167
  def keyTyped(self,*args):
168
    pass
169
  def keyPressed(self,*args):
170
    try:
171
      self(*args)
172
    except java.lang.Throwable, t:
173
      pass
174
  def keyReleased(self,*args):
175
    pass
176

    
177
class FunctionRunnable(java.lang.Runnable):
178
  def __init__(self,fn, *args):
179
    self.__fn = fn
180
    self.__args = args
181

    
182
  def run(self):
183
    self.__fn(*self.__args)
184

    
185
  def __call__(self):
186
    self.__fn(*self.__args)
187

    
188

    
189
class ProgressBarWithTaskStatus(Observer):
190
  def __init__(self, name, progressBar, labelProgress=None):
191
    self.taskStatus = ToolsLocator.getTaskStatusManager().createDefaultSimpleTaskStatus(name)
192
    self.progressBar = progressBar
193
    self.labelProgress = labelProgress
194
    self.progressBar.setMinimum(0)
195
    self.progressBar.setMaximum(100)
196
    self.progressBar.setValue(0)
197
    self.taskStatus.addObserver(self)
198

    
199
  def getTaskStatus(self):
200
    return self.taskStatus
201

    
202
  def update(self, taskStatus, notification):
203
    if not javax.swing.SwingUtilities.isEventDispatchThread():
204
      javax.swing.SwingUtilities.invokeLater(
205
        FunctionRunnable(
206
          self.updateGUI,
207
          taskStatus.isRunning(),
208
          taskStatus.getCompleted(),
209
          taskStatus.getLabel()
210
        )
211
      )
212
    else:
213
      self.updateGUI(
214
        taskStatus.isRunning(),
215
        taskStatus.getCompleted(),
216
        taskStatus.getLabel()
217
      )
218

    
219
  def updateGUI(self, isRunning, current, label):
220
    if not isRunning:
221
        self.progressBar.setIndeterminate(False)
222
        self.progressBar.setValue(100)
223
        self.labelProgress.setText("")
224
        return
225
    self.progressBar.setIndeterminate(self.taskStatus.isIndeterminate())
226
    self.progressBar.setValue(current)
227
    if self.labelProgress != None:
228
      self.labelProgress.setText(label)
229

    
230
def load_image(afile):
231
  if not isinstance(afile,java.io.File):
232
    if isinstance(afile,tuple) or isinstance(afile,list):
233
      afile = getResource(*afile)
234
    afile = java.io.File(str(afile))
235
  return javax.imageio.ImageIO.read(afile)
236

    
237
def load_icon(afile):
238
  if not isinstance(afile,java.io.File):
239
    if isinstance(afile,tuple) or isinstance(afile,list):
240
      afile = getResource(*afile)
241
    afile = java.io.File(str(afile))
242
  return javax.swing.ImageIcon(javax.imageio.ImageIO.read(afile))
243

    
244
class ComboItem(object):
245
  def __init__(self, label="", value=None):
246
    self.__label = label
247
    self.__value = value
248

    
249
  def getLabel(self):
250
    return self.__label
251

    
252
  def getValue(self):
253
    return self.__value
254

    
255
  __str__ = getLabel
256
  __repr__ = getLabel
257

    
258
class FormComponent(object):
259

    
260
  def load_image(self, afile):
261
    return load_image(afile)
262

    
263
  def load_icon(self, afile):
264
    return load_icon(afile)
265

    
266
  def autobind(self):
267
    members = inspect.getmembers(self)
268
    for methodName, method in members:
269
      if methodName.endswith("_click"):
270
        name = methodName[0:-len("_click")]
271
        component = getattr(self,name, None)
272
        if isinstance(component, javax.swing.JComboBox):
273
          component.addActionListener(ActionListenerAdapter(method,methodName))
274
        elif isinstance(component, javax.swing.AbstractButton):
275
          component.addActionListener(ActionListenerAdapter(method,methodName))
276

    
277
      elif methodName.endswith("_change"):
278
        name = methodName[0:-len("_change")]
279
        component = getattr(self,name, None)
280
        if isinstance(component, javax.swing.JComboBox):
281
          component.addItemListener(ItemListenerAdapter(method,methodName))
282
        elif isinstance(component, javax.swing.JList):
283
          component.addListSelectionListener(ListSelectionListenerAdapter(method,methodName))
284
        elif isinstance(component, javax.swing.JRadioButton):
285
          component.addItemListener(ItemListenerAdapter(method,methodName))
286
        elif isinstance(component, javax.swing.JSpinner):
287
          component.addChangeListener(ChangeListenerAdapter(method,methodName))
288
        elif isinstance(component, javax.swing.text.JTextComponent):
289
          component.getDocument().addDocumentListener(DocumentListenerAdapter(method,methodName))
290
        elif isinstance(component, javax.swing.AbstractButton):
291
          component.addActionListener(ActionListenerAdapter(method,methodName))
292

    
293
      elif methodName.endswith("_perform"):
294
        name = methodName[0:-len("_perform")]
295
        component = getattr(self,name, None)
296
        if isinstance(component, javax.swing.Timer):
297
          component.addActionListener(ActionListenerAdapter(method,methodName))
298

    
299
      elif methodName.endswith("_focusGained"):
300
        name = methodName[0:-len("_focusGained")]
301
        component = getattr(self,name, None)
302
        if component!=None:
303
          addFocusListener = getattr(component,"addFocusListener",None)
304
          if addFocusListener !=None:
305
            addFocusListener(FocusGainedListenerAdapter(method,methodName))
306

    
307
      elif methodName.endswith("_focusLost"):
308
        name = methodName[0:-len("_focusLost")]
309
        component = getattr(self,name, None)
310
        if component!=None:
311
          addFocusListener = getattr(component,"addFocusListener",None)
312
          if addFocusListener !=None:
313
            addFocusListener(FocusLostListenerAdapter(method,methodName))
314

    
315
      elif methodName.endswith("_mouseClick"):
316
        name = methodName[0:-len("_mouseClick")]
317
        component = getattr(self,name, None)
318
        if component!=None:
319
          addMouseListener = getattr(component,"addMouseListener",None)
320
          if addMouseListener !=None:
321
            addMouseListener(MouseListenerAdapter(method,methodName))
322

    
323
      elif methodName.endswith("_keyPressed"):
324
        name = methodName[0:-len("_keyPressed")]
325
        component = getattr(self,name, None)
326
        if component!=None:
327
          addKeyListener = getattr(component,"addKeyListener",None)
328
          if addKeyListener != None:
329
            addKeyListener(KeyPressedListenerAdapter(method,methodName))
330

    
331

    
332
def fixFormPanelResourceLoader():
333
  appResourceLoader = JETARegistry.lookup(ResourceLoader.COMPONENT_ID)
334
  if appResourceLoader == None:
335
    print "Can't access to the resource loader of Forms panels."
336
  else:
337
    urls = array((ScriptingLocator.getManager().getUserFolder().getFile().toURL(),), URL)
338
    appResourceLoader.setClassLoader(URLClassLoader(urls))
339

    
340
class FormPanel(FormComponent):
341

    
342
  def __init__(self,formfile=None):
343
    FormComponent.__init__(self)
344
    fixFormPanelResourceLoader()
345
    self._panel = None
346
    if formfile!=None:
347
      self.load(formfile)
348

    
349
  def getRootPane(self):
350
    return self.asJComponent().getParent().getParent()
351

    
352
  def getPreferredSize(self):
353
    return self.asJComponent().getPreferredSize()
354

    
355
  def setPreferredSize(self, withOrDimension, height=None):
356
    if height == None:
357
      self.asJComponent().setPreferredSize(withOrDimension)
358
    else:
359
      self.asJComponent().setPreferredSize(java.awt.Dimension(withOrDimension,height))
360

    
361
  def getPanel(self):
362
    return self.asJComponent()
363

    
364
  def asJComponent(self):
365
    return self._panel
366

    
367
  def hide(self):
368
    self._panel.setVisible(False)
369

    
370
  def __getattr__(self, name):
371
    if name in ("__members__", "__methods__"):
372
      raise AttributeError("FormPanel",name)
373
    attr = self._panel.getComponentByName(name)
374
    if attr == None:
375
      raise AttributeError("FormPanel",name)
376
    return attr
377

    
378
  def load(self, formfile):
379
    if not isinstance(formfile,java.io.File):
380
      if isinstance(formfile,tuple) or isinstance(formfile,list):
381
        formfile = getResource(*formfile)
382
      formfile = java.io.File(str(formfile))
383
    #print "FormPanel.load(%s)" % formfile
384
    self._panel = com.jeta.forms.components.panel.FormPanel( java.io.FileInputStream(formfile) )
385
    #print "FormPanel.load: _panel=%s" % self._panel
386
    self.autobind()
387

    
388
  def btnClose_click(self,*args):
389
    self.hide()
390

    
391
  def showWindow(self, title):
392
    self._panel.setVisible(True)
393
    windowManager = ToolsSwingLocator.getWindowManager()
394
    windowManager.showWindow(self.asJComponent(),title, windowManager.MODE.WINDOW)
395

    
396
  def showTool(self, title):
397
    self._panel.setVisible(True)
398
    windowManager = ToolsSwingLocator.getWindowManager()
399
    windowManager.showWindow(self.asJComponent(),title, windowManager.MODE.TOOL)
400

    
401
  def showDialog(self, title):
402
    self._panel.setVisible(True)
403
    windowManager = ToolsSwingLocator.getWindowManager()
404
    windowManager.showWindow(self._panel,title, windowManager.MODE.DIALOG)
405