Exemplo n.º 1
0
def load_functions():
    global List
    # right now we are going to assume that this code is only ever run on UNIX
    if 'HOME' in os.environ:
        path = _make_path()
        if os.access(path, os.F_OK & os.R_OK & os.X_OK):
            os.chdir(path)
            for f in glob.glob('*'):
                file = open(f)
                lines = file.readlines()
                function_list[f] = lines  # don't think that this is right.
                file.close()
            return 1
        else:
            GtkExtra.message_box(title='Loading Error',
                                 message='Could read the file',
                                 buttons=('OK', ))
            return 0
    else:
        # popup a message box saying that there wasn't anything
        # in the file.
        GtkExtra.message_box(
            title='Loading Error',
            message=
            'Environment is not configure. Can\'t HOME environment variable.',
            buttons=('OK', ))
    return 0
Exemplo n.º 2
0
	def save_image(self,mi=None):
		try:
			window=self.canvas.get_window()		
			self.image=GdkImlib.create_image_from_drawable(window,None,-50,-100,4500,1800)
			self.image.save_image(self.imgfname)
		except:
			GtkExtra.message_box('No Image available',("OK",))
Exemplo n.º 3
0
 def dnd_drag_data_received(w, context, x, y, data, info, time):
     if data and data.format == 8:
         msg = "Drop data of type %s was:\n\n%s" % \
               (data.target, data.data)
         GtkExtra.message_box(
             "Drop", msg,
             ("Continue with life in\n" + "spite of this oppression", ))
Exemplo n.º 4
0
	def run_script(self, fname):
		if not fname or os.path.exists(fname):
			GtkExtra.message_box("Run","Invalid filename",("OK",))
			return
		args = GtkExtra.input_box("Arguments",
				 "Enter any command line arguments")
		if args == None: return
		os.system(VT_CMD+'python "'+fname+'" ' + args + ' &')
Exemplo n.º 5
0
 def run_script(self, fname):
     if not fname or os.path.exists(fname):
         GtkExtra.message_box("Run", "Invalid filename", ("OK", ))
         return
     args = GtkExtra.input_box("Arguments",
                               "Enter any command line arguments")
     if args == None: return
     os.system(VT_CMD + 'python "' + fname + '" ' + args + ' &')
Exemplo n.º 6
0
 def raster_open_by_name(self,filename):
     dataset = gdal.Open(filename)
     if dataset is None:
         GtkExtra.message_box('Error',
                              'Unable to open '+filename,
                              ('OK',) )
         return None
     return dataset
Exemplo n.º 7
0
 def file_selection_ok(_button, fs=win):
     fname = fs.get_filename()
     try:
         camera.load(fname)
     except IOError:
         text = 'Load from file ' + fname + ' failed!'
         GtkExtra.message_box("Load failed!", text, ("Close", ))
     else:
         fs.hide()
Exemplo n.º 8
0
    def process_help(self, action, widget):
        GtkExtra.message_box("Test Application",
                             """Test Application for Python-Gtk.
		This is free software.
		This application tests key press events and text display.
		Any entered key (printable character) is displayed on
		screen. <F1> toggle medium and bold font. <F2> permits
		to change font size.
		""", ("OK", ),
                             pixmap='question.xpm')
Exemplo n.º 9
0
def auto_file_load(filename):
    if filename != None:
        try:
            d = load_data_file(filename)
        except:
            GtkExtra.message_box(title="Error Loading File",
                                 message="Problems Loading File: " + file_name,
                                 buttons=("OK", ))
            return None
        setup_loaded_chart(d, filename)
Exemplo n.º 10
0
    def file_open_by_name(self, filename, *args):
        if filename[len(filename)-4:] == '.shp':
            self.file_open_shape_by_name(filename)
            return
        
        if filename[len(filename)-4:] == '.SHP':
            self.file_open_shape_by_name(filename)
            return
        
        dataset = gdal.Open(filename)
        if dataset is None:
            GtkExtra.message_box('Error',
                      'Unable to open '+filename,
                      ('OK',) )
            return

        self.files.append(dataset)

        for band_index in range(1,1+min(3,dataset.RasterCount)):
            band = dataset.GetRasterBand(band_index)
            
            interp = band.GetRasterColorInterpretation()
            if interp == gdal.GCI_PaletteIndex:
                raster = gview.GvRaster(dataset=dataset,sample=gview.SMSample,
                                        real=band_index)
            else:
                raster = gview.GvRaster(dataset=dataset,real=band_index)
            
            raster.set_name(filename)
            gview.undo_register(raster)
            
            view = self.view_manager.get_active_view()
            if view is None:
                return
            
            options = []
            if gview.get_preference('gcp_warp_mode') is not None \
               and gview.get_preference('gcp_warp_mode') == 'no':
                options.append(('raw','yes'))
                
            raster_layer = gview.GvRasterLayer(raster, options)
                
            if interp == gdal.GCI_RedBand:
                raster_layer.texture_mode_set(1,(1.0,0.0,0.0,1.0))
                raster_layer.blend_mode_set(gview.RL_BLEND_ADD,1,1)
            elif interp == gdal.GCI_GreenBand:
                raster_layer.texture_mode_set(1,(0.0,1.0,0.0,1.0))
                raster_layer.blend_mode_set(gview.RL_BLEND_ADD,1,1)
            elif interp == gdal.GCI_BlueBand:
                raster_layer.texture_mode_set(1,(0.0,0.0,1.0,1.0))
                raster_layer.blend_mode_set(gview.RL_BLEND_ADD,1,1)
                
            view.add_layer(raster_layer)
Exemplo n.º 11
0
	def reload_file(self, fname):
		if not os.path.isfile(fname):
			GtkExtra.message_box("File Not Found", fname +
					     " was not found.", ("OK",))
		dir = os.path.dirname(fname)
		base = os.path.basename(fname)
		if dir not in sys.path: sys.path.insert(0, dir)
		if   string.lower(base[-3:]) == '.py':  base = base[:-3]
		elif string.lower(base[-4:]) == '.pyc': base = base[:-4]
		if not sys.modules.has_key(base):
			self.interp.run('import ' + base)
		else:
			self.interp.run('import ' + base)
			self.interp.run('reload(' + base + ')')
Exemplo n.º 12
0
 def reload_file(self, fname):
     if not os.path.isfile(fname):
         GtkExtra.message_box("File Not Found", fname + " was not found.",
                              ("OK", ))
     dir = os.path.dirname(fname)
     base = os.path.basename(fname)
     if dir not in sys.path: sys.path.insert(0, dir)
     if string.lower(base[-3:]) == '.py': base = base[:-3]
     elif string.lower(base[-4:]) == '.pyc': base = base[:-4]
     if not sys.modules.has_key(base):
         self.interp.run('import ' + base)
     else:
         self.interp.run('import ' + base)
         self.interp.run('reload(' + base + ')')
Exemplo n.º 13
0
def new_button(_b):
    # popup little dialog to get the title of the function.
    # if user enters a name, start the editor so that the new function can be
    # edited.
    name = GtkExtra.input_box(title="Enter Function Name",
                              message="Name of the new function is? ",
                              modal=TRUE)
    if function_list.has_key(name):
        GtkExtra.message_box(title="Duplicate Function Name",
                             message="Function name already exists",
                             buttons=("OK"),
                             pixmap=None,
                             modal=TRUE)
    else:
        run_editor_on(_make_path() + '/' + name)
Exemplo n.º 14
0
	def process_help(self, action, widget):
		dlg=GtkExtra.message_box("Test Application",
					 "Test Application for Python-Gtk.\n" +
					 "This is free software.\n" +
					 "This application tests mouse and " +
					 "key press events.", ("OK",),
					 pixmap='question.xpm')
Exemplo n.º 15
0
 def file_save(self, mi=None):
     if self.new:
         self.file_saveas()
         return
     try:
         pos = 0
         length = self.text.get_length()
         fd = open(self.fname, "w")
         while pos < length:
             buf = self.text.get_chars(pos, min(pos + BLOCK_SIZE, length))
             if buf != None: fd.write(buf)
             pos = pos + BLOCK_SIZE
         self.dirty = 0
     except:
         GtkExtra.message_box("Save", "Error saving file " + self.fname,
                              ("OK", ))
Exemplo n.º 16
0
    def create_header(self,filename):
        fmt=self.format_list[self.format_menu.get_history()]
        dtype=self.type_list[self.type_menu.get_history()]
        dr=gdal.GetDriverByName(fmt)
        tlist=string.split(dr.GetMetadata()["DMD_CREATIONDATATYPES"])
        if dtype not in tlist:
            gvutils.error(fmt+' format does not support '+dtype+' data type!')
            return
        
        if fmt == 'PAux':
            self.create_paux_header(filename,dtype)
        else:
            fname,ext = os.path.splitext(filename)
            vrtname = fname+'.vrt'
                
            fname=pgufilesel.GetFileName(title="Select VRT Save Name",
                                         default_filename=vrtname)
            if fname is None:
                return
            if os.path.exists(fname):
	        resp = GtkExtra.message_box('Confirmation', \
		        fname + ' exists. Overwrite?', ('Yes','No'))
                if resp == 'No':
                    return
            lines=self.create_vrt_lines(filename)
            fh=open(fname,'w')
            fh.writelines(lines)
            fh.close()
 def showConfirm(self, mess):
     i = GtkExtra.message_box(
         "GtkSnapshot", str(mess),
         [self.trans_text("YES"),
          self.trans_text("NO")])
     if i == self.trans_text("YES"): return 1
     return 0
Exemplo n.º 18
0
 def ok_button(self, _button):
     entry = self.combo1.entry.get_text()
     bars = self.spinbutton1.get_value_as_int()
     if bars < 0:
         bars = 0
     if entry not in VALID_COMBO_ITEMS:
         GtkExtra.message_box(title='Bad Value',
                              message='Scale is invalid',
                              buttons=('OK', ),
                              pixmap=None,
                              modal=TRUE)
         self.selection['extrabars'] = None
         self.selection['scale'] = None
     else:
         self.selection['extrabars'] = bars
         self.selection['scale'] = entry
     self.quit()
Exemplo n.º 19
0
	def file_save(self, mi=None):
		if self.new:
			self.file_saveas()
			return
		try:
			pos = 0
			length = self.text.get_length()
			fd = open(self.fname, "w")
			while pos < length:
				buf = self.text.get_chars(pos,
						  min(pos+BLOCK_SIZE, length))
				if buf != None: fd.write(buf)
				pos = pos + BLOCK_SIZE
			self.dirty = 0
		except:
			GtkExtra.message_box("Save", "Error saving file " +
					     self.fname, ("OK",))
Exemplo n.º 20
0
    def create_paux_header(self,filename,datatype):    
	(path, ext) = os.path.splitext(filename)
	auxname = path + ".aux"
	if os.path.isfile(auxname):
	    resp = GtkExtra.message_box('Confirmation', \
		    auxname + ' exists. Overwrite?', ('Yes','No'))
            if resp == 'No':
                return

	# Take the image parameters
	header = long(self.header_entry.get_text())
	width = long(self.width_entry.get_text())
	height = long(self.height_entry.get_text())
	bands = long(self.bands_entry.get_text())
        aux_type_dict={'Byte':'8U','Int16':'16S','UInt16':'16U',
                       'Float32':'32R'}
	aux_type_list = ['8U', '16S', '16U', '32R']
	type = aux_type_dict[datatype]
	gdaltype = gdal.GetDataTypeByName(datatype)
	interleaving = self.interleave_list[self.interleave_menu.get_history()]
	datasize = gdal.GetDataTypeSize(gdaltype) / 8

	# Calculate offsets
	pixel_offset = []
	line_offset = []
	image_offset = []
	if interleaving is 'Pixel':
	    for i in range(bands):
		pixel_offset.append(datasize * bands)
		line_offset.append(datasize * width * bands)
		image_offset.append(header + datasize * i)
	elif interleaving is 'Band':
	    for i in range(bands):
		pixel_offset.append(datasize)
		line_offset.append(datasize * width)
		image_offset.append(header + datasize * width * height * i)
	elif interleaving is 'Line':
	    for i in range(bands):
		pixel_offset.append(datasize)
		line_offset.append(datasize * width * bands)
		image_offset.append(header + datasize * width * i)
	else:
	    raise 'Unsupported interleaving type!'
	
	aux_swap_list = ['Swapped', 'Unswapped']
	swap = aux_swap_list[self.swap_menu.get_history()]

	# Write out the auxilary file
	aux = open(auxname, "wt")
	aux.write("AuxilaryTarget: " +  os.path.basename(filename) + '\n')
	aux.write("RawDefinition: " + str(width) + ' ' \
		+ str(height) + ' ' + str(bands) + '\n')
	for i in range(bands):
	    aux.write("ChanDefinition-" + str(i + 1) + ': ' + type + ' ' \
		    + str(image_offset[i]) + ' ' + str(pixel_offset[i]) \
		    + ' ' + str(line_offset[i]) + ' ' + swap + '\n')
	aux.close()
	aux = None
Exemplo n.º 21
0
def load_file(file_name):
    try:
        d = load_data_file(file_name)
    except Exception, msg:
        mb = GtkExtra.message_box(title="Error Loading File",
                                  message="Problems Loading File: " +
                                  file_name,
                                  buttons=("OK", ))
        return None
Exemplo n.º 22
0
 def load_file(self, fname):
     try:
         fd = open(fname)
         self.text.freeze()
         self.text.delete_text(0, self.text.get_length())
         buf = fd.read(BLOCK_SIZE)
         while buf != '':
             self.text.insert_defaults(buf)
             buf = fd.read(BLOCK_SIZE)
         self.text.thaw()
         self.text.get_vadjustment().set_value(0)
         self.text.queue_draw()
         self.set_title(os.path.basename(fname))
         self.fname = fname
         self.dirty = 0
         self.new = 0
     except:
         GtkExtra.message_box('Edit', "Can't open " + fname, ("OK", ))
Exemplo n.º 23
0
 def chk_save(self):
     if self.dirty:
         ret = GtkExtra.message_box(
             "Unsaved File", (self.fname or "Untitled") +
             " has not been saved\n" + "Do you want to save it?",
             ("Yes", "No", "Cancel"))
         if ret == None or ret == "Cancel": return 1
         if ret == "Yes": self.file_save()
     return 0
Exemplo n.º 24
0
	def load_file(self, fname):
		try:
			fd = open(fname)
			self.text.freeze()
			self.text.delete_text(0, self.text.get_length())
			buf = fd.read(BLOCK_SIZE)
			while buf != '':
				self.text.insert_defaults(buf)
				buf = fd.read(BLOCK_SIZE)
			self.text.thaw()
			self.text.get_vadjustment().set_value(0)
			self.text.queue_draw()
			self.set_title(os.path.basename(fname))
			self.fname = fname
			self.dirty = 0
			self.new = 0
		except:
			GtkExtra.message_box('Edit', "Can't open " + fname,
					     ("OK",))
Exemplo n.º 25
0
	def chk_save(self):
		if self.dirty:
			ret = GtkExtra.message_box("Unsaved File",
						   (self.fname or "Untitled")+
						   " has not been saved\n" +
						   "Do you want to save it?",
						   ("Yes", "No", "Cancel"))
			if ret == None or ret == "Cancel": return 1
			if ret == "Yes": self.file_save()
		return 0
Exemplo n.º 26
0
 def process_help(self, action, widget):
     dlg = GtkExtra.message_box(
         "Test Application",
         "Test Application for Python-Gtk.\n"
         + "This is free software.\n"
         + "This application tests mouse and "
         + "key press events.",
         ("OK",),
         pixmap="question.xpm",
     )
Exemplo n.º 27
0
    def att_update_cb(self, *args):
        if self.text_contents == self.text.get_chars(0, -1):
            return

        if self.selected_shape is None:
            return

        shapes = self.layer.get_parent()
        shape = shapes[self.selected_shape]
        if shape is None:
            return

        shape = shape.copy()

        lines = string.split(self.text.get_chars(0, -1), '\n')
        for line in lines:
            tokens = string.split(line, ':', 1)
            if len(tokens) == 2:
                value = string.strip(tokens[1])
                shape.set_property(tokens[0], value)
                property_exists = 0
                for cprop in shapes.get_schema():
                    if cprop[0] == tokens[0]:
                        property_exists = 1
                if property_exists != 1:
                    ftype = self.new_field_types[
                        self.new_field_type_menu.get_history()]

                    response = \
                       GtkExtra.message_box('Confirmation',
                         'Create new ' + ftype + '-type property ' + tokens[0] + '?' ,
                                            ('Yes','No'))
                    if response == 'Yes':
                        try:
                            fwidth = int(self.new_field_width_entry.get_text())
                        except:
                            gvutils.error('Field width must be an integer!')
                            continue

                        if ftype == 'float':
                            try:
                                fprec = int(
                                    self.new_field_width_entry.get_text())
                            except:
                                gvutils.error(
                                    'Precision width must be an integer!')
                                continue
                        else:
                            fprec = 0

                        shapes.add_field(tokens[0], ftype, fwidth, fprec)

        shapes[self.selected_shape] = shape
        self.gui_update()
Exemplo n.º 28
0
def create_about(_button):
    v4l_version = camera.get_value('V4L Driver version')
    if v4l_version == '':
        v4l_version = 'unknown'
    cpia_version = camera.get_value('CPIA Version')
    cpia_pnpid = camera.get_value('CPIA PnP-ID')
    vp_version = camera.get_value('VP-Version')
    text="CPiA camera control program (Version:"+cpia_control_version+")"+\
          "\nV4l Driver version: "+v4l_version+\
"""
Detected Camera:
"""+\
    "CPIA Version: "+cpia_version+"\n"+\
    "CPIA Pn-PID: "+cpia_pnpid+"\n"+\
    "VP-Version: "+vp_version+"\n"+\
"""
See http://webcam.sourceforge.net/ for more details

Copyright(c) 1999/2000/2004 by
Peter Pregler ([email protected])
"""
    GtkExtra.message_box("About CPiA control", text, ("Close", ))
Exemplo n.º 29
0
    def att_update_cb(self,*args):
        if self.text_contents == self.text.get_chars(0,-1):
            return

        if self.selected_shape is None:
            return

        shapes = self.layer.get_parent()
        shape = shapes[self.selected_shape]
        if shape is None:
            return

        shape = shape.copy()
        
        lines = string.split(self.text.get_chars(0,-1),'\n')
        for line in lines:
            tokens = string.split(line,':',1)
            if len(tokens) == 2:
                value = string.strip(tokens[1])
                shape.set_property(tokens[0],value)
                property_exists=0
                for cprop in shapes.get_schema():
                    if cprop[0] == tokens[0]:
                        property_exists=1
                if property_exists != 1:
                    ftype = self.new_field_types[self.new_field_type_menu.get_history()]
                       
                    response = \
                       GtkExtra.message_box('Confirmation',
                         'Create new ' + ftype + '-type property ' + tokens[0] + '?' ,
                                            ('Yes','No'))
                    if response == 'Yes':
                        try:
                            fwidth = int(self.new_field_width_entry.get_text())
                        except:
                            gvutils.error('Field width must be an integer!')
                            continue
                        
                        if ftype == 'float':
                            try:
                                fprec = int(self.new_field_width_entry.get_text())
                            except:
                                gvutils.error('Precision width must be an integer!')
                                continue
                        else:
                            fprec = 0
                            
                        shapes.add_field(tokens[0],ftype,fwidth,fprec)

        shapes[self.selected_shape] = shape
        self.gui_update()
Exemplo n.º 30
0
 def process_file(self, action, widget):
     if action == 0:
         print "File:<unknwon>"
     elif action == 1:
         print "File:New"
     elif action == 2:
         print "File:Open"
         print GtkExtra.file_open_box(modal=FALSE), "chosen"
     elif action == 3:
         print "FileSave"
         dlg = GtkExtra.message_box("Test Application", "Not implemented", ("OK",), pixmap="bomb.xpm")
     elif action == 4:
         print "File:Save As"
         print GtkExtra.file_save_box(modal=FALSE), "chosen"
     elif action == 5:
         print "File:Close"
     elif action == 6:
         print "File:Exit"
         mainquit()
Exemplo n.º 31
0
def file_realtime_update(_menu, entry_name):
    if real_time_entries.has_key(entry_name):
        script = real_time_entries[entry_name]
        if os.access(script, os.R_OK | os.X_OK):
            name = os.tempnam('/tmp/', 'chase')
            f = open(name, 'w+')
            f.close()
            rt = os.system(script + " -t " + name)
            if rt != 0:
                mb = GtkExtra.message_box(title="Error loading data from %s" %
                                          (entry_name, ),
                                          message="External source failed",
                                          buttons=("OK", ))
                return None
            print "system command returned %d" % (rt, )
            update_chase_with_realtime_data(name)
            #os.unlink(name)
        else:
            sys.write.stderr("Can't find the script: %s" % (script, ))
    else:
        sys.write.stderr("realtime update called with invalid name: %s" \
                         % (entry_name,))
Exemplo n.º 32
0
	def help_about(self, mi):
		GtkExtra.message_box("Domain Draw Window", "Copyright (C) 2003  " +
				     "Yu Huang\n" +
				     "This program is covered by the GPL.",
				     ("OK",))
 def showMessage(self, mess):
     GtkExtra.message_box("gAnim8 Conversion Tool",
                          self.trans_text(str(mess)), ["Ok"])
Exemplo n.º 34
0
	def help_about(self, mi):
		GtkExtra.message_box("Edit Window", "Copyright (C) 1998  " +
				     "James Henstridge\n" +
				     "This program is covered by the GPL>=2",
				     ("OK",))
Exemplo n.º 35
0
 def help_about(self, mi):
     GtkExtra.message_box(
         "Edit Window", "Copyright (C) 1998  " + "James Henstridge\n" +
         "This program is covered by the GPL>=2", ("OK", ))
Exemplo n.º 36
0
def __gtk(title, message):
    import GtkExtra  # @UnresolvedImport
    GtkExtra.message_box(title, message, ['Ok'])
Exemplo n.º 37
0
def __gtk(title, message):
    import GtkExtra
    GtkExtra.message_box(title, message, ['Ok'])
Exemplo n.º 38
0
    def export_cb(self,*args):
        ipfile=self.frame_dict['Files'].get('Input')
        opfile=self.frame_dict['Files'].get('Output')
        if os.path.isfile(opfile):
            resp=GtkExtra.message_box('Confirmation',opfile +
                                      ' exists.  Overwrite?',('Yes','No'))
            if resp == 'No':
                return
        elif len(opfile) == 0:
            gvutils.error('No output filename entered!')
            return
            
        use_viewscale=0
        
        rast = gdal.OpenShared(ipfile, gdalconst.GA_ReadOnly)
        if rast is None:
            if len(ipfile) == 0:
                gvutils.error('Please specify an input file!')
            else:
                gvutils.error('Unable to open ' + ipfile + ' as a GDAL supported file!')
            return

        # Catch the case where the input file consists of in-memory VRT lines
        # and the output format is also VRT.  In this case, the new VRT would
        # no longer be valid once openev was exited because the input file
        # is not on disk (filename looks something like '<VRTDataset....').
        # If the user is just exporting the file as-is, simply copying the
        # original lines to disk will suffice.  However, if they want to
        # window or scale, we'd need more complicated manipulations.  For now,
        # give an error message in that case.
        opformat=self.format_list[self.format_menu.get_history()]
        
        if (ipfile[0] == '<') and (opformat == 'VRT'):
            if self.res_list[self.res_menu.get_history()] != 'Full':
                msg='Only full output resolution is currently\n'+\
                    'supported for export of in-memory VRTs\n'+\
                    'to on-disk VRTs.'
                gvutils.error(msg)
                return
            
            if ( (self.button_dict['Mode'].get_active()) and
                ((self.button_dict['IP_window'].get_active()) or
                (self.button_dict['Scale'].get_active()) or
                (len(self.optentry.get_text()) > 0))):
                msg='Scaling, windowing, and advanced creation\n'+\
                    'options are not yet supported for export of \n'+\
                    'in-memory VRTs to on-disk VRTs'
                gvutils.error(msg)
                return
                
            linelist=string.split(ipfile,'\n')
            newlinelist=[]
            for item in linelist:
                newlinelist.append(item+'\n')
            fh=open(opfile,'w')
            fh.writelines(newlinelist)
            fh.close()
            
            ovrs=self._overview_list[self.overview_menu.get_history()]
            if ovrs != 'None':
                outds=gdal.OpenShared(opfile)
                if outds is None:
                    gvutils.error('Error opening '+opfile+' for overview creation!')
                    return
                
                progress = pguprogress.PGUProgressDialog( 'Building overviews...',
                                                  cancel = gtk.TRUE )
                if ovrs is 'Nearest':
                    outds.BuildOverviews( "nearest",
                                       callback = progress.ProgressCB )
                else:
                    outds.BuildOverviews( "average_magphase",
                                       callback = progress.ProgressCB )
                progress.destroy()
            
            return
        
            
        
        vrt_opts=vrtutils.VRTCreationOptions(rast.RasterCount)

        if self._geocode_list[self.geocoding_menu.get_history()] == 'GCP':
            vrt_opts.set_geopref('gcps')
        elif self._geocode_list[self.geocoding_menu.get_history()] == 'Geotransform':
            vrt_opts.set_geopref('geotransform')

        band_list = None
        
        # Scale the output file according to the current view's
        # min/max
        if self.button_dict['Scale'].get_active():
            try:
                clayer = self.app.sel_manager.get_active_layer()
                if clayer.get_parent().get_dataset().GetDescription() != ipfile:
                    wtxt = 'Input file and active layer file names do not match- may '
                    wtxt = wtxt + 'result in unexpected scaling!'
                    gvutils.warning(wtxt)
                if gvutils.is_of_class(clayer.__class__,'GvRasterLayer') == 0:
                    gvutils.warning('Active layer is not a raster- view scaling ignored!')
                else:
                    src_count=clayer.sources
                    band_list = []
                    RGBAlist=['Red','Green','Blue','Alpha']
                    for src in range(src_count):
                        # layer sources are numbered 0...3; band sources are numbered 1,2,...
                        src_bandnum=clayer.get_data(src).get_band_number()
                        band_list.append(src_bandnum)
                        vrt_opts.set_scaling((clayer.min_get(src),clayer.max_get(src),0,255),(src_bandnum,))
                        vrt_opts.set_datatype(gdal.GDT_Byte,(src_bandnum,))
                        if src_count == 3:
                            vrt_opts.set_color_interp(RGBAlist[src],
                                                      (src_bandnum,))

                    # src_count is three even when there is an alpha channel
                    # for rgb/rgba case
                    if src_count == 3:
                        try:
                            src=3
                            src_bandnum=clayer.get_data(src).get_band_number()
                            band_list.append(src_bandnum)
                            vrt_opts.set_scaling((clayer.min_get(src),
                                                  clayer.max_get(src),0,255),
                                                 (src_bandnum,))
                            vrt_opts.set_datatype(gdal.GDT_Byte,(src_bandnum,))
                            vrt_opts.set_color_interp(RGBAlist[src],
                                                      (src_bandnum,))
                        except:
                            pass

                    use_viewscale=1
                    if clayer.get_mode()==gview.RLM_COMPLEX:
                        # This doesn't deal with complex yet...                        
                        gvutils.error('View scaling option is not yet supported for complex data!')
                        return
                    elif rast._band[0].DataType == gdal.GDT_CInt16:
                        # This doesn't deal with complex yet...                        
                        gvutils.error('View scaling option is not yet supported for complex data!')
                        return
                    elif rast._band[0].DataType == gdal.GDT_CInt32:
                        # This doesn't deal with complex yet...                        
                        gvutils.error('View scaling option is not yet supported for complex data!')
                        return
                    elif rast._band[0].DataType == gdal.GDT_CFloat32:
                        # This doesn't deal with complex yet...                        
                        gvutils.error('View scaling option is not yet supported for complex data!')
                        return
                    elif rast._band[0].DataType == gdal.GDT_CFloat64:
                        # This doesn't deal with complex yet...                        
                        gvutils.error('View scaling option is not yet supported for complex data!')
                        return                    
            except:
                gvutils.error('Unable to find active raster layer for scaling!')
                return

        # Get windowing options
        if self.button_dict['IP_window'].get_active():
            try:
                spix=int(self.frame_dict['IP_window'].entry_dict['start_pix'].get_text())
                sline=int(self.frame_dict['IP_window'].entry_dict['start_line'].get_text())
                npix=int(self.frame_dict['IP_window'].entry_dict['num_pix'].get_text())
                nlines=int(self.frame_dict['IP_window'].entry_dict['num_lines'].get_text())
                if (spix < 0) or (sline < 0):
                    gvutils.error('Negative start pixel and/or line!  Aborting...')
                    return
                if (npix+spix > rast.RasterXSize):
                    gvutils.error('Window is too large (last column in input: '+str(rast.RasterXSize)+')! Aborting...')
                    return
                if (nlines+sline > rast.RasterYSize):
                    gvutils.error('Window is too large (last row in input: '+str(rast.RasterYSize)+')! Aborting...')
                    return
            except:
                gvutils.error('Error retrieving window options!  Aborting...')
                return
        else:
            spix=0
            sline=0
            npix=rast.RasterXSize
            nlines=rast.RasterYSize

        vrt_opts.set_src_window((spix,sline,npix,nlines))

        if self.res_list[self.res_menu.get_history()] != 'Full':
            ovrlevel=int(self.res_list[self.res_menu.get_history()][2])
        else:
            ovrlevel=1

        vrt_opts.set_dst_window((0,0,npix/ovrlevel,nlines/ovrlevel))

        vrt_tree=vrtutils.serializeDataset(rast,vrt_opts,band_list)
        vrt_lines=gdal.SerializeXMLTree(vrt_tree)
        vrtdataset=gdal.Open(vrt_lines)
        
        driver=gdal.GetDriverByName(opformat)

        # Parse creation options:
        optstr=string.strip(self.optentry.get_text())
        if len(optstr) > 0:
            # should be able to deal with several
            # types of entries, eg.
            # 'TILED=YES','TFW=YES'
            # and
            # TILED=YES,TFW=YES

            if optstr[0] in ["'",'"']:
                split1=string.split(optstr,",")
                copts=[]
                for item in split1:
                    if len(item) > 2:
                        copts.append(item[1:len(item)-1])
            else:    
                copts=string.split(optstr,',')
        else:
            copts=[]
    
        progress = pguprogress.PGUProgressDialog( 'Export to '+opfile,
                                                  cancel = gtk.TRUE )
        progress.SetDefaultMessage("translated")

        outdataset=driver.CreateCopy(opfile,vrtdataset,
                                     options=copts,
                                     callback=progress.ProgressCB)
        if outdataset is None:
            progress.destroy()
            gvutils.error('Unable to create output file '+opfile)
            return
        
        ovrs=self._overview_list[self.overview_menu.get_history()]
        if ovrs is 'Nearest':
            progress.SetDefaultMessage("overviews built")
            outdataset.BuildOverviews( "nearest",
                                       callback = progress.ProgressCB )
   
        elif ovrs is 'Average':
            progress.SetDefaultMessage("overviews built")
            outdataset.BuildOverviews( "average_magphase",
                                       callback = progress.ProgressCB )
            
        progress.destroy()
Exemplo n.º 39
0
    def export_cb(self, *args):
        ipfile = self.frame_dict['Files'].get('Input')
        opfile = self.frame_dict['Files'].get('Output')
        if os.path.isfile(opfile):
            resp = GtkExtra.message_box('Confirmation',
                                        opfile + ' exists.  Overwrite?',
                                        ('Yes', 'No'))
            if resp == 'No':
                return
        elif len(opfile) == 0:
            gvutils.error('No output filename entered!')
            return

        use_viewscale = 0

        rast = gdal.OpenShared(ipfile, gdalconst.GA_ReadOnly)
        if rast is None:
            if len(ipfile) == 0:
                gvutils.error('Please specify an input file!')
            else:
                gvutils.error('Unable to open ' + ipfile +
                              ' as a GDAL supported file!')
            return

        # Catch the case where the input file consists of in-memory VRT lines
        # and the output format is also VRT.  In this case, the new VRT would
        # no longer be valid once openev was exited because the input file
        # is not on disk (filename looks something like '<VRTDataset....').
        # If the user is just exporting the file as-is, simply copying the
        # original lines to disk will suffice.  However, if they want to
        # window or scale, we'd need more complicated manipulations.  For now,
        # give an error message in that case.
        opformat = self.format_list[self.format_menu.get_history()]

        if (ipfile[0] == '<') and (opformat == 'VRT'):
            if self.res_list[self.res_menu.get_history()] != 'Full':
                msg='Only full output resolution is currently\n'+\
                    'supported for export of in-memory VRTs\n'+\
                    'to on-disk VRTs.'
                gvutils.error(msg)
                return

            if ((self.button_dict['Mode'].get_active())
                    and ((self.button_dict['IP_window'].get_active()) or
                         (self.button_dict['Scale'].get_active()) or
                         (len(self.optentry.get_text()) > 0))):
                msg='Scaling, windowing, and advanced creation\n'+\
                    'options are not yet supported for export of \n'+\
                    'in-memory VRTs to on-disk VRTs'
                gvutils.error(msg)
                return

            linelist = string.split(ipfile, '\n')
            newlinelist = []
            for item in linelist:
                newlinelist.append(item + '\n')
            fh = open(opfile, 'w')
            fh.writelines(newlinelist)
            fh.close()

            ovrs = self._overview_list[self.overview_menu.get_history()]
            if ovrs != 'None':
                outds = gdal.OpenShared(opfile)
                if outds is None:
                    gvutils.error('Error opening ' + opfile +
                                  ' for overview creation!')
                    return

                progress = pguprogress.PGUProgressDialog(
                    'Building overviews...', cancel=gtk.TRUE)
                if ovrs is 'Nearest':
                    outds.BuildOverviews("nearest",
                                         callback=progress.ProgressCB)
                else:
                    outds.BuildOverviews("average_magphase",
                                         callback=progress.ProgressCB)
                progress.destroy()

            return

        vrt_opts = vrtutils.VRTCreationOptions(rast.RasterCount)

        if self._geocode_list[self.geocoding_menu.get_history()] == 'GCP':
            vrt_opts.set_geopref('gcps')
        elif self._geocode_list[
                self.geocoding_menu.get_history()] == 'Geotransform':
            vrt_opts.set_geopref('geotransform')

        band_list = None

        # Scale the output file according to the current view's
        # min/max
        if self.button_dict['Scale'].get_active():
            try:
                clayer = self.app.sel_manager.get_active_layer()
                if clayer.get_parent().get_dataset().GetDescription(
                ) != ipfile:
                    wtxt = 'Input file and active layer file names do not match- may '
                    wtxt = wtxt + 'result in unexpected scaling!'
                    gvutils.warning(wtxt)
                if gvutils.is_of_class(clayer.__class__, 'GvRasterLayer') == 0:
                    gvutils.warning(
                        'Active layer is not a raster- view scaling ignored!')
                else:
                    src_count = clayer.sources
                    band_list = []
                    RGBAlist = ['Red', 'Green', 'Blue', 'Alpha']
                    for src in range(src_count):
                        # layer sources are numbered 0...3; band sources are numbered 1,2,...
                        src_bandnum = clayer.get_data(src).get_band_number()
                        band_list.append(src_bandnum)
                        vrt_opts.set_scaling(
                            (clayer.min_get(src), clayer.max_get(src), 0, 255),
                            (src_bandnum, ))
                        vrt_opts.set_datatype(gdal.GDT_Byte, (src_bandnum, ))
                        if src_count == 3:
                            vrt_opts.set_color_interp(RGBAlist[src],
                                                      (src_bandnum, ))

                    # src_count is three even when there is an alpha channel
                    # for rgb/rgba case
                    if src_count == 3:
                        try:
                            src = 3
                            src_bandnum = clayer.get_data(
                                src).get_band_number()
                            band_list.append(src_bandnum)
                            vrt_opts.set_scaling((clayer.min_get(src),
                                                  clayer.max_get(src), 0, 255),
                                                 (src_bandnum, ))
                            vrt_opts.set_datatype(gdal.GDT_Byte,
                                                  (src_bandnum, ))
                            vrt_opts.set_color_interp(RGBAlist[src],
                                                      (src_bandnum, ))
                        except:
                            pass

                    use_viewscale = 1
                    if clayer.get_mode() == gview.RLM_COMPLEX:
                        # This doesn't deal with complex yet...
                        gvutils.error(
                            'View scaling option is not yet supported for complex data!'
                        )
                        return
                    elif rast._band[0].DataType == gdal.GDT_CInt16:
                        # This doesn't deal with complex yet...
                        gvutils.error(
                            'View scaling option is not yet supported for complex data!'
                        )
                        return
                    elif rast._band[0].DataType == gdal.GDT_CInt32:
                        # This doesn't deal with complex yet...
                        gvutils.error(
                            'View scaling option is not yet supported for complex data!'
                        )
                        return
                    elif rast._band[0].DataType == gdal.GDT_CFloat32:
                        # This doesn't deal with complex yet...
                        gvutils.error(
                            'View scaling option is not yet supported for complex data!'
                        )
                        return
                    elif rast._band[0].DataType == gdal.GDT_CFloat64:
                        # This doesn't deal with complex yet...
                        gvutils.error(
                            'View scaling option is not yet supported for complex data!'
                        )
                        return
            except:
                gvutils.error(
                    'Unable to find active raster layer for scaling!')
                return

        # Get windowing options
        if self.button_dict['IP_window'].get_active():
            try:
                spix = int(self.frame_dict['IP_window'].
                           entry_dict['start_pix'].get_text())
                sline = int(self.frame_dict['IP_window'].
                            entry_dict['start_line'].get_text())
                npix = int(self.frame_dict['IP_window'].entry_dict['num_pix'].
                           get_text())
                nlines = int(self.frame_dict['IP_window'].
                             entry_dict['num_lines'].get_text())
                if (spix < 0) or (sline < 0):
                    gvutils.error(
                        'Negative start pixel and/or line!  Aborting...')
                    return
                if (npix + spix > rast.RasterXSize):
                    gvutils.error(
                        'Window is too large (last column in input: ' +
                        str(rast.RasterXSize) + ')! Aborting...')
                    return
                if (nlines + sline > rast.RasterYSize):
                    gvutils.error('Window is too large (last row in input: ' +
                                  str(rast.RasterYSize) + ')! Aborting...')
                    return
            except:
                gvutils.error('Error retrieving window options!  Aborting...')
                return
        else:
            spix = 0
            sline = 0
            npix = rast.RasterXSize
            nlines = rast.RasterYSize

        vrt_opts.set_src_window((spix, sline, npix, nlines))

        if self.res_list[self.res_menu.get_history()] != 'Full':
            ovrlevel = int(self.res_list[self.res_menu.get_history()][2])
        else:
            ovrlevel = 1

        vrt_opts.set_dst_window((0, 0, npix / ovrlevel, nlines / ovrlevel))

        vrt_tree = vrtutils.serializeDataset(rast, vrt_opts, band_list)
        vrt_lines = gdal.SerializeXMLTree(vrt_tree)
        vrtdataset = gdal.Open(vrt_lines)

        driver = gdal.GetDriverByName(opformat)

        # Parse creation options:
        optstr = string.strip(self.optentry.get_text())
        if len(optstr) > 0:
            # should be able to deal with several
            # types of entries, eg.
            # 'TILED=YES','TFW=YES'
            # and
            # TILED=YES,TFW=YES

            if optstr[0] in ["'", '"']:
                split1 = string.split(optstr, ",")
                copts = []
                for item in split1:
                    if len(item) > 2:
                        copts.append(item[1:len(item) - 1])
            else:
                copts = string.split(optstr, ',')
        else:
            copts = []

        progress = pguprogress.PGUProgressDialog('Export to ' + opfile,
                                                 cancel=gtk.TRUE)
        progress.SetDefaultMessage("translated")

        outdataset = driver.CreateCopy(opfile,
                                       vrtdataset,
                                       options=copts,
                                       callback=progress.ProgressCB)
        if outdataset is None:
            progress.destroy()
            gvutils.error('Unable to create output file ' + opfile)
            return

        ovrs = self._overview_list[self.overview_menu.get_history()]
        if ovrs is 'Nearest':
            progress.SetDefaultMessage("overviews built")
            outdataset.BuildOverviews("nearest", callback=progress.ProgressCB)

        elif ovrs is 'Average':
            progress.SetDefaultMessage("overviews built")
            outdataset.BuildOverviews("average_magphase",
                                      callback=progress.ProgressCB)

        progress.destroy()
Exemplo n.º 40
0
 def file_selection_ok(_button, fs=win):
     fname = fs.get_filename()
     if camera.save(fname):
         text = 'Save to file ' + fname + ' failed!'
         GtkExtra.message_box("Save failed!", text, ("Close", ))
     fs.hide()
Exemplo n.º 41
0
    def process_file(self, action, widget):
        if action == 0: print "File:<unknown>"
        elif action == 1:
            print "File:New"
            self.w_text.freeze()
            self.w_text.set_point(0)
            self.w_text.insert_defaults("*new file*")
            self.w_text.thaw()
            #self.w_text.queueDraw()
        elif action == 2:
            print "File:Open"
            print GtkExtra.file_open_box(modal=FALSE), "chosen"
        elif action == 3:
            print "File:Save"
            GtkExtra.message_box("Test Application",
                                 "Not Implemented", ("OK", ),
                                 pixmap='bomb.xpm')
        elif action == 4:
            print "File:Save As"
            print GtkExtra.message_box(modal=FALSE), "chosen"
        elif action == 5:
            print "File:Close"
            GtkExtra.message_box("Test Application",
                                 "Not Implemented", ("OK", ),
                                 pixmap='bomb.xpm')
        elif action == 6:
            print "File:Exit"
            mainquit()

    def process_edit(self, action, widget):
        if action == 0: print "Edit:<unknown>"
Exemplo n.º 42
0
            if fname:
                try:
                    f = open(fname, "r")
                except IOError:
                    return
                self.w_text.freeze()
                while TRUE:
                    line = f.readline()
                    if line == "":
                        break
                    self.w_text.insert_defaults(line)
                self.w_text.thaw()
        elif action == 3:
            print "File:Save"
            GtkExtra.message_box("Test Application",
                                 "Not implemented",
                                 pixmap='bomb.xpm')
        elif action == 4:
            print "File:Save As"
            print GtkExtra.file_save_box(modal=FALSE), "chosen"
        elif action == 5:
            print "File:Close"
        elif action == 6:
            print "File:Exit"
            mainquit()

    def process_edit(self, action, widget):
        if action == 0: print "Edit:<unknown>"
        elif action == 1:
            print "Edit:Cut"
            self.w_text.cut_clipboard(0)
Exemplo n.º 43
0
			if fname:
				try:
					f=open(fname, "r")
				except IOError:
					return
				self.w_text.freeze()
				while TRUE:
					line = f.readline()
					if line == "":
						break
					self.w_text.insert_defaults(line)
				self.w_text.thaw()
		elif action == 3:
			print "File:Save"
			GtkExtra.message_box("Test Application",
					     "Not implemented",
					     pixmap='bomb.xpm')
		elif action == 4:
			print "File:Save As"
			print GtkExtra.file_save_box(modal=FALSE), "chosen"
		elif action == 5:
			print "File:Close"
		elif action == 6:
			print "File:Exit"
			mainquit()

	def process_edit(self, action, widget):
		if action == 0: print "Edit:<unknown>"
		elif action == 1:
			print "Edit:Cut"
			self.w_text.cut_clipboard(0)