Package teamwork :: Package widgets :: Package htmlViewer :: Module mfxutil
[hide private]
[frames] | no frames]

Source Code for Module teamwork.widgets.htmlViewer.mfxutil

  1  ## vim:ts=4:et:nowrap 
  2  ## 
  3  ##---------------------------------------------------------------------------## 
  4  ## 
  5  ## PySol -- a Python Solitaire game 
  6  ## 
  7  ## Copyright (C) 2003 Markus Franz Xaver Johannes Oberhumer 
  8  ## Copyright (C) 2002 Markus Franz Xaver Johannes Oberhumer 
  9  ## Copyright (C) 2001 Markus Franz Xaver Johannes Oberhumer 
 10  ## Copyright (C) 2000 Markus Franz Xaver Johannes Oberhumer 
 11  ## Copyright (C) 1999 Markus Franz Xaver Johannes Oberhumer 
 12  ## Copyright (C) 1998 Markus Franz Xaver Johannes Oberhumer 
 13  ## All Rights Reserved. 
 14  ## 
 15  ## This program is free software; you can redistribute it and/or modify 
 16  ## it under the terms of the GNU General Public License as published by 
 17  ## the Free Software Foundation; either version 2 of the License, or 
 18  ## (at your option) any later version. 
 19  ## 
 20  ## This program is distributed in the hope that it will be useful, 
 21  ## but WITHOUT ANY WARRANTY; without even the implied warranty of 
 22  ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 23  ## GNU General Public License for more details. 
 24  ## 
 25  ## You should have received a copy of the GNU General Public License 
 26  ## along with this program; see the file COPYING. 
 27  ## If not, write to the Free Software Foundation, Inc., 
 28  ## 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 
 29  ## 
 30  ## Markus F.X.J. Oberhumer 
 31  ## <markus@oberhumer.com> 
 32  ## http://www.oberhumer.com/pysol 
 33  ## 
 34  ##---------------------------------------------------------------------------## 
 35   
 36   
 37  # imports 
 38  import sys, os, operator, re, string, time, types, htmlentitydefs 
 39  import traceback 
 40   
 41  try: 
 42      from cPickle import Pickler, Unpickler, UnpicklingError 
 43  except ImportError: 
 44      from pickle import Pickler, Unpickler, UnpicklingError 
 45  thread = None 
 46  try: 
 47      import thread 
 48  except: 
 49      thread = None 
 50  if os.name == "mac": 
 51      import macfs, MACFS 
 52  win32api = None 
 53   
 54  from mfxtools import * 
 55   
 56   
 57  # /*********************************************************************** 
 58  # // exceptions 
 59  # ************************************************************************/ 
 60   
 61  # work around a Mac problem 
 62  ##EnvError = EnvironmentError 
 63  EnvError = (IOError, OSError, os.error,) 
 64   
 65   
66 -class SubclassResponsibility(Exception):
67 pass
68 69 70 # /*********************************************************************** 71 # // misc. util 72 # ************************************************************************/ 73
74 -def static(f, *args, **kw):
75 if args: 76 a = tuple([f.im_class()] + list(args)) 77 else: 78 a = (f.im_class(),) 79 return apply(f, a, kw)
80 81
82 -def ifelse(expr, val1, val2):
83 if expr: 84 return val1 85 return val2
86 87
88 -def merge_dict(dict1, dict2, merge_none=1):
89 for k, v in dict2.items(): 90 if dict1.has_key(k): 91 if type(dict1[k]) is type(v): 92 dict1[k] = v 93 elif dict1[k] is None and merge_none: 94 dict1[k] = v
95 96 97 # this is a quick hack - we definitely need Unicode support...
98 -def latin1_to_ascii(n):
99 ## FIXME: rewrite this for better speed 100 n = string.replace(n, "\xc4", "Ae") 101 n = string.replace(n, "\xd6", "Oe") 102 n = string.replace(n, "\xdc", "Ue") 103 n = string.replace(n, "\xe4", "ae") 104 n = string.replace(n, "\xf6", "oe") 105 n = string.replace(n, "\xfc", "ue") 106 return n
107 108 109 htmlentitydefs_i = {} 110
111 -def latin1_to_html(n):
112 global htmlentitydefs_i 113 if not htmlentitydefs_i: 114 for k, v in htmlentitydefs.entitydefs.items(): 115 htmlentitydefs_i[v] = "&" + k + ";" 116 s, g = "", htmlentitydefs_i.get 117 for c in n: 118 s = s + g(c, c) 119 return s
120 121
122 -def hexify(s):
123 return "%02x"*len(s) % tuple(map(ord, s))
124 125 126 # /*********************************************************************** 127 # // misc. portab stuff 128 # ************************************************************************/ 129
130 -def getusername():
131 if os.name == "nt": 132 return win32_getusername() 133 user = string.strip(os.environ.get("USER","")) 134 if not user: 135 user = string.strip(os.environ.get("LOGNAME","")) 136 return user
137 138
139 -def gethomedir():
140 if os.name == "nt": 141 return win32_gethomedir() 142 home = string.strip(os.environ.get("HOME", "")) 143 if not home or not os.path.isdir(home): 144 home = os.curdir 145 return os.path.abspath(home)
146 147
148 -def getprefdir(package, home=None):
149 if os.name == "nt": 150 return win32_getprefdir(package, appname, home) 151 if os.name == "mac": 152 vrefnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk, MACFS.kPreferencesFolderType, 0) 153 fss = macfs.FSSpec((vrefnum, dirid, ":" + appname)) 154 return fss.as_pathname() 155 if home is None: 156 home = gethomedir() 157 return os.path.join(home, "." + string.lower(package))
158 159 160 # high resolution clock() and sleep() 161 uclock = time.clock 162 usleep = time.sleep 163 if os.name == "posix": 164 uclock = time.time 165 166 167 # /*********************************************************************** 168 # // memory util 169 # ************************************************************************/ 170
171 -def destruct(obj):
172 # assist in breaking circular references 173 if obj is not None: 174 assert type(obj) is types.InstanceType 175 for k in obj.__dict__.keys(): 176 obj.__dict__[k] = None
177 ##del obj.__dict__[k] 178 179 180 # /*********************************************************************** 181 # // 182 # ************************************************************************/ 183
184 -class Struct:
185 - def __init__(self, **kw):
186 self.__dict__.update(kw)
187
188 - def __str__(self):
189 return str(self.__dict__)
190
191 - def __setattr__(self, key, value):
192 if not self.__dict__.has_key(key): 193 raise AttributeError, key 194 self.__dict__[key] = value
195
196 - def addattr(self, **kw):
197 for key in kw.keys(): 198 if hasattr(self, key): 199 raise AttributeError, key 200 self.__dict__.update(kw)
201
202 - def update(self, dict):
203 for key in dict.keys(): 204 if not self.__dict__.has_key(key): 205 raise AttributeError, key 206 self.__dict__.update(dict)
207
208 - def clear(self):
209 for key in self.__dict__.keys(): 210 t = type(key) 211 if t is types.ListType: 212 self.__dict__[key] = [] 213 elif t is types.TupleType: 214 self.__dict__[key] = () 215 elif t is types.DictType: 216 self.__dict__[key] = {} 217 else: 218 self.__dict__[key] = None
219
220 - def copy(self):
221 c = Struct() 222 c.__class__ = self.__class__ 223 c.__dict__.update(self.__dict__) 224 return c
225 226 227 # /*********************************************************************** 228 # // keyword argument util 229 # ************************************************************************/ 230 231 # update keyword arguments with default arguments
232 -def kwdefault(kw, **defaults):
233 for k, v in defaults.items(): 234 if not kw.has_key(k): 235 kw[k] = v
236 237
238 -class KwStruct:
239 - def __init__(self, kw={}, **defaults):
240 if isinstance(kw, KwStruct): 241 kw = kw.__dict__ 242 if isinstance(defaults, KwStruct): 243 defaults = defaults.__dict__ 244 if defaults: 245 kw = kw.copy() 246 for k, v in defaults.items(): 247 if not kw.has_key(k): 248 kw[k] = v 249 self.__dict__.update(kw)
250
251 - def __setattr__(self, key, value):
252 if not self.__dict__.has_key(key): 253 raise AttributeError, key 254 self.__dict__[key] = value
255
256 - def __getitem__(self, key):
257 return getattr(self, key)
258
259 - def get(self, key, default=None):
260 return self.__dict__.get(key, default)
261
262 - def getKw(self):
263 return self.__dict__
264 265 266 # /*********************************************************************** 267 # // pickling support 268 # ************************************************************************/ 269
270 -def pickle(obj, filename, binmode=0):
271 f = None 272 try: 273 f = open(filename, "wb") 274 p = Pickler(f, binmode) 275 p.dump(obj) 276 f.close(); f = None 277 ##print "Pickled", filename 278 finally: 279 if f: f.close()
280 281
282 -def unpickle(filename):
283 f, obj = None, None 284 try: 285 f = open(filename, "rb") 286 p = Unpickler(f) 287 x = p.load() 288 f.close(); f = None 289 obj = x 290 ##print "Unpickled", filename 291 finally: 292 if f: f.close() 293 return obj
294 295 296 # /*********************************************************************** 297 # // 298 # ************************************************************************/ 299
300 -def spawnv(file, args=()):
301 if not args: 302 args = () 303 args = (file,) + tuple(args) 304 # 305 if not os.path.isfile(file): 306 raise os.error, str(file) 307 mode = os.stat(file)[0] 308 if not (mode & 0100): 309 return 0 310 # 311 if os.name == "posix": 312 pid = os.fork() 313 if pid == -1: 314 raise os.error, "fork failed" 315 if pid != 0: 316 # parent 317 try: 318 os.waitpid(pid, 0) 319 except: 320 pass 321 return 1 322 # child 323 # 1) close all files 324 for fd in range(255, -1, -1): 325 try: 326 os.close(fd) 327 except: 328 pass 329 # 2) open stdin, stdout and stderr to /dev/null 330 try: 331 fd = os.open("/dev/null", os.O_RDWR) 332 os.dup(fd) 333 os.dup(fd) 334 except: 335 pass 336 # 3) fork again and exec program 337 try: 338 if os.fork() == 0: 339 try: 340 os.setpgrp() 341 except: 342 pass 343 os.execv(file, args) 344 except: 345 pass 346 # 4) exit 347 while 1: 348 os._exit(0) 349 return 0
350 351
352 -def spawnvp(file, args=()):
353 if file and os.path.isabs(file): 354 try: 355 if spawnv(file, args): 356 return file 357 except: 358 ##if traceback: traceback.print_exc() 359 pass 360 return None 361 # 362 path = os.environ.get("PATH", "") 363 path = string.splitfields(path, os.pathsep) 364 for dir in path: 365 try: 366 if dir and os.path.isdir(dir): 367 f = os.path.join(dir, file) 368 try: 369 if spawnv(f, args): 370 return f 371 except: 372 ##if traceback: traceback.print_exc() 373 pass 374 except: 375 ##if traceback: traceback.print_exc() 376 pass 377 return None
378 379 380 # /*********************************************************************** 381 # // 382 # ************************************************************************/ 383 384 __SOUND_MIXER = () 385
386 -def spawnSystemSoundMixer(query=0):
387 global __SOUND_MIXER 388 if query: 389 return __SOUND_MIXER is not None 390 MIXERS = () 391 if os.name == "posix": 392 MIXERS = (("kmix", None), ("gmix", None),) 393 for name, args in MIXERS: 394 try: 395 f = spawnvp(name, args) 396 if f: 397 __SOUND_MIXER = (f, args) 398 return 1 399 except: 400 if traceback: traceback.print_exc() 401 pass 402 __SOUND_MIXER = None 403 return 0
404 405
406 -def spawnSystemDisplaySettings():
407 if os.name == "nt": 408 return win32_spawnSystemDisplaySettings() 409 return 0
410 411 412 # /*********************************************************************** 413 # // 414 # ************************************************************************/ 415
416 -def openURL(url):
417 if os.name == "nt": 418 return win32_openURL(url) 419 if 0 and os.name == "posix": 420 ns = (url,) 421 ns = ("-remote", "openURL(" + url + ",new-window)",) 422 BROWSERS = ( 423 ("kfmclient", ("openURL", url,)), 424 ("netscape", ns), 425 ("netscape4", ns), 426 ("netscape3", ns), 427 ("/opt/netscape-3.04/netscape304", ns), 428 ("mozilla", (url,)), 429 ("gnome-help-browser", (url,)), 430 ) 431 for name, args in BROWSERS: 432 try: 433 ##print name, args 434 if spawnvp(name, args): 435 return 1 436 except: 437 pass 438 return 0
439 440 441 # /*********************************************************************** 442 # // memory debugging 443 # ************************************************************************/ 444 445
446 -def dumpmem(dump_all_objects=1):
447 var = {} 448 if dump_all_objects: 449 for m in sys.modules.keys(): 450 mod = sys.modules[m] 451 if mod: 452 for k in mod.__dict__.keys(): 453 v = mod.__dict__[k] 454 if type(v) in (types.ClassType, types.InstanceType): 455 var[k] = v 456 else: 457 for k, v in vars().items() + globals().items(): 458 var[k] = v 459 info = [] 460 for k in var.keys(): 461 n = sys.getrefcount(var[k]) 462 v = var[k] 463 if type(v) is types.ClassType: 464 ## FIXME: we must subtract the number of methods 465 ## FIXME: we must also subtract the number of subclasses 466 pass 467 if n > 3: 468 # we seem to create 3 (???) extra references while in this function 469 info.append(n - 3, k, v) 470 var[k] = None 471 var = None 472 info.sort() 473 info.reverse() 474 sum = 0 475 for count, varname, value in info: 476 sum = sum + count 477 if type(value) in ( 478 types.InstanceType, types.ModuleType, types.ClassType, 479 types.NoneType, types.FunctionType, types.StringType 480 ): 481 valuestr = repr(value)[:40] 482 else: 483 valuestr = "n/a" 484 print "%7d %-25s %s" % (count, varname, valuestr) 485 print "%7d ---TOTAL---" % (sum)
486 487 488 489 # /*********************************************************************** 490 # // debugging 491 # ************************************************************************/ 492 493
494 -def callername():
495 try: 496 raise Exception 497 except: 498 return sys.exc_traceback.tb_frame.f_back.f_back.f_code.co_name
499
500 -def callerglobals():
501 try: 502 raise Exception 503 except: 504 return sys.exc_traceback.tb_frame.f_back.f_back.f_globals
505
506 -def uplevel(name):
507 print __name__, callerglobals()[name], callerglobals()["__name__"]
508