Exemplo n.º 1
0
int
main (int argc, char **argv)
{
    GOptionContext *ctx;
    GError *error = NULL;

    /* First parse the arguments that are passed to us */

    ctx = g_option_context_new (NULL);
    g_option_context_add_main_entries (ctx, options, NULL);

    if (!g_option_context_parse (ctx,
                                 &argc, &argv, &error))
    {
        g_printerr ("%s", error->message);
        return 1;
    }

    g_option_context_free (ctx);

    GPtrArray *tests = g_ptr_array_new ();

    if (all_tests)
    {
        GFile *test_dir = g_file_new_for_path (MUTTER_PKGDATADIR "/tests");

        if (!find_metatests_in_directory (test_dir, tests, &error))
        {
            g_printerr ("Error enumerating tests: %s\n", error->message);
            return 1;
        }
    }
    else
    {
        int i;
        char *curdir = g_get_current_dir ();

        for (i = 1; i < argc; i++)
        {
            if (g_path_is_absolute (argv[i]))
                g_ptr_array_add (tests, g_strdup (argv[i]));
            else
                g_ptr_array_add (tests, g_build_filename (curdir, argv[i], NULL));
        }

        g_free (curdir);
    }

    /* Then initalize mutter with a different set of arguments */

    char *fake_args[] = { NULL, (char *)"--wayland" };
    fake_args[0] = argv[0];
    char **fake_argv = fake_args;
    int fake_argc = 2;

    char *basename = g_path_get_basename (argv[0]);
    char *dirname = g_path_get_dirname (argv[0]);
    if (g_str_has_prefix (basename, "lt-"))
        test_client_path = g_build_filename (dirname, "../mutter-test-client", NULL);
    else
        test_client_path = g_build_filename (dirname, "mutter-test-client", NULL);
    g_free (basename);
    g_free (dirname);

    ctx = meta_get_option_context ();
    if (!g_option_context_parse (ctx, &fake_argc, &fake_argv, &error))
    {
        g_printerr ("mutter: %s\n", error->message);
        exit (1);
    }
    g_option_context_free (ctx);

    meta_plugin_manager_load ("default");

    meta_init ();
    meta_register_with_session ();

    RunTestsInfo info;
    info.tests = (char **)tests->pdata;
    info.n_tests = tests->len;

    g_idle_add (run_tests, &info);

    return meta_run ();
}
Exemplo n.º 2
0
static BraseroBurnResult
brasero_cdrecord_set_argv_record (BraseroCDRecord *cdrecord,
				  GPtrArray *argv, 
				  GError **error)
{
	guint speed;
	BraseroBurnFlag flags;
	BraseroCDRecordPrivate *priv;
	BraseroTrackType *type = NULL;

	priv = BRASERO_CD_RECORD_PRIVATE (cdrecord);

	if (priv->immediate) {
		g_ptr_array_add (argv, g_strdup ("-immed"));
		g_ptr_array_add (argv, g_strdup_printf ("minbuf=%i", priv->minbuf));
	}

	if (brasero_job_get_speed (BRASERO_JOB (cdrecord), &speed) == BRASERO_BURN_OK) {
		gchar *speed_str;

		speed_str = g_strdup_printf ("speed=%d", speed);
		g_ptr_array_add (argv, speed_str);
	}

	brasero_job_get_flags (BRASERO_JOB (cdrecord), &flags);
	if (flags & BRASERO_BURN_FLAG_OVERBURN)
		g_ptr_array_add (argv, g_strdup ("-overburn"));
	if (flags & BRASERO_BURN_FLAG_BURNPROOF)
		g_ptr_array_add (argv, g_strdup ("driveropts=burnfree"));
	if (flags & BRASERO_BURN_FLAG_MULTI)
		g_ptr_array_add (argv, g_strdup ("-multi"));

	/* NOTE: This write mode is necessary for all CLONE images burning */
	if (flags & BRASERO_BURN_FLAG_RAW)
		g_ptr_array_add (argv, g_strdup ("-raw96r"));

	/* NOTE1: DAO can't be used if we're appending to a disc */
	/* NOTE2: CD-text cannot be written in tao mode (which is the default)
	 * NOTE3: when we don't want wodim to use stdin then we give the audio
	 * file on the command line. Otherwise we use the .inf */
	if (flags & BRASERO_BURN_FLAG_DAO)
		g_ptr_array_add (argv, g_strdup ("-dao"));

	type = brasero_track_type_new ();
	brasero_job_get_input_type (BRASERO_JOB (cdrecord), type);

	if (brasero_job_get_fd_in (BRASERO_JOB (cdrecord), NULL) == BRASERO_BURN_OK) {
		BraseroBurnResult result;
		int buffer_size;
		goffset sectors;
		
		/* we need to know what is the type of the track (audio / data) */
		result = brasero_job_get_input_type (BRASERO_JOB (cdrecord), type);
		if (result != BRASERO_BURN_OK) {
			brasero_track_type_free (type);

			BRASERO_JOB_LOG (cdrecord, "Imager doesn't seem to be ready")
			g_set_error (error,
				     BRASERO_BURN_ERROR,
				     BRASERO_BURN_ERROR_GENERAL,
				     _("An internal error occurred"));
			return BRASERO_BURN_ERR;
		}
		
		/* ask the size */
		result = brasero_job_get_session_output_size (BRASERO_JOB (cdrecord),
							      &sectors,
							      NULL);
		if (result != BRASERO_BURN_OK) {
			brasero_track_type_free (type);

			BRASERO_JOB_LOG (cdrecord, "The size of the session cannot be retrieved")
			g_set_error (error,
				     BRASERO_BURN_ERROR,
				     BRASERO_BURN_ERROR_GENERAL,
				     _("An internal error occurred"));
			return BRASERO_BURN_ERR;
		}

		/* we create a buffer depending on the size 
		 * buffer 4m> < 64m and is 1/25th of size otherwise */
		buffer_size = sectors * 2352 / 1024 / 1024 / 25;
		if (buffer_size > 32)
			buffer_size = 32;
		else if (buffer_size < 4)
			buffer_size = 4;

		g_ptr_array_add (argv, g_strdup_printf ("fs=%im", buffer_size));
		if (brasero_track_type_get_has_image (type)) {
			BraseroImageFormat format;

			format = brasero_track_type_get_image_format (type);
			if (format == BRASERO_IMAGE_FORMAT_BIN) {
				g_ptr_array_add (argv, g_strdup_printf ("tsize=%"G_GINT64_FORMAT"s", sectors));
				g_ptr_array_add (argv, g_strdup ("-data"));
				g_ptr_array_add (argv, g_strdup ("-nopad"));
				g_ptr_array_add (argv, g_strdup ("-"));
			}
			else {
				brasero_track_type_free (type);
				BRASERO_JOB_NOT_SUPPORTED (cdrecord);
			}
		}
		else if (brasero_track_type_get_has_stream (type)) {
			g_ptr_array_add (argv, g_strdup ("-audio"));
			g_ptr_array_add (argv, g_strdup ("-useinfo"));
			g_ptr_array_add (argv, g_strdup ("-text"));

			result = brasero_cdrecord_write_infs (cdrecord,
							      argv,
							      error);
			if (result != BRASERO_BURN_OK) {
				brasero_track_type_free (type);
				return result;
			}
		}
		else {
			brasero_track_type_free (type);
			BRASERO_JOB_NOT_SUPPORTED (cdrecord);
		}
	}
	else if (brasero_track_type_get_has_stream (type)) {
		BraseroBurnResult result;
		GSList *tracks;

		g_ptr_array_add (argv, g_strdup ("fs=16m"));
		g_ptr_array_add (argv, g_strdup ("-audio"));
		g_ptr_array_add (argv, g_strdup ("-pad"));
	
		g_ptr_array_add (argv, g_strdup ("-useinfo"));
		g_ptr_array_add (argv, g_strdup ("-text"));

		result = brasero_cdrecord_write_infs (cdrecord,
						      NULL,
						      error);
		if (result != BRASERO_BURN_OK) {
			brasero_track_type_free (type);
			return result;
		}

		tracks = NULL;
		brasero_job_get_tracks (BRASERO_JOB (cdrecord), &tracks);
		for (; tracks; tracks = tracks->next) {
			BraseroTrack *track;
			gchar *path;

			track = tracks->data;
			path = brasero_track_stream_get_source (BRASERO_TRACK_STREAM (track), FALSE);
			g_ptr_array_add (argv, path);
		}
	}
	else if (brasero_track_type_get_has_image (type)) {
		BraseroTrack *track = NULL;
		BraseroImageFormat format;

		brasero_job_get_current_track (BRASERO_JOB (cdrecord), &track);
		if (!track) {
			brasero_track_type_free (type);
			BRASERO_JOB_NOT_READY (cdrecord);
		}

		format = brasero_track_type_get_image_format (type);
		if (format == BRASERO_IMAGE_FORMAT_NONE) {
			gchar *image_path;

			image_path = brasero_track_image_get_source (BRASERO_TRACK_IMAGE (track), FALSE);
			if (!image_path) {
				brasero_track_type_free (type);
				BRASERO_JOB_NOT_READY (cdrecord);
			}

			g_ptr_array_add (argv, g_strdup ("fs=16m"));
			g_ptr_array_add (argv, g_strdup ("-data"));
			g_ptr_array_add (argv, g_strdup ("-nopad"));
			g_ptr_array_add (argv, image_path);
		}
		else if (format == BRASERO_IMAGE_FORMAT_BIN) {
			gchar *isopath;

			isopath = brasero_track_image_get_source (BRASERO_TRACK_IMAGE (track), FALSE);
			if (!isopath) {
				brasero_track_type_free (type);
				BRASERO_JOB_NOT_READY (cdrecord);
			}

			g_ptr_array_add (argv, g_strdup ("fs=16m"));
			g_ptr_array_add (argv, g_strdup ("-data"));
			g_ptr_array_add (argv, g_strdup ("-nopad"));
			g_ptr_array_add (argv, isopath);
		}
		else if (format == BRASERO_IMAGE_FORMAT_CLONE) {
			gchar *rawpath;

			rawpath = brasero_track_image_get_source (BRASERO_TRACK_IMAGE (track), FALSE);
			if (!rawpath) {
				brasero_track_type_free (type);
				BRASERO_JOB_NOT_READY (cdrecord);
			}

			g_ptr_array_add (argv, g_strdup ("fs=16m"));
			g_ptr_array_add (argv, g_strdup ("-clone"));
			g_ptr_array_add (argv, rawpath);
		}
		else if (format == BRASERO_IMAGE_FORMAT_CUE) {
			gchar *cue_str;
			gchar *cuepath;
			gchar *parent;

			cuepath = brasero_track_image_get_toc_source (BRASERO_TRACK_IMAGE (track), FALSE);
			if (!cuepath) {
				brasero_track_type_free (type);
				BRASERO_JOB_NOT_READY (cdrecord);
			}

			parent = g_path_get_dirname (cuepath);
			brasero_process_set_working_directory (BRASERO_PROCESS (cdrecord), parent);
			g_free (parent);

			/* we need to check endianness */
			if (brasero_track_image_need_byte_swap (BRASERO_TRACK_IMAGE (track)))
				g_ptr_array_add (argv, g_strdup ("-swab"));

			g_ptr_array_add (argv, g_strdup ("fs=16m"));

			/* This is to make sure the CD-TEXT stuff gets written */
			g_ptr_array_add (argv, g_strdup ("-text"));

			cue_str = g_strdup_printf ("cuefile=%s", cuepath);
			g_ptr_array_add (argv, cue_str);
			g_free (cuepath);
		}
		else {
			brasero_track_type_free (type);
			BRASERO_JOB_NOT_SUPPORTED (cdrecord);
		}
	}
	else {
		brasero_track_type_free (type);
		BRASERO_JOB_NOT_SUPPORTED (cdrecord);
	}

	brasero_track_type_free (type);

	brasero_job_set_current_action (BRASERO_JOB (cdrecord),
					BRASERO_BURN_ACTION_START_RECORDING,
					NULL,
					FALSE);
	return BRASERO_BURN_OK;
}
void convert_babylonfile(const char *filename, print_info_t print_info, bool strip_html)
{			
	struct stat stats;
	if (g_stat (filename, &stats) == -1)
	{
		print_info("File not exist!\n");
		return;
	}
	gchar *basefilename = g_path_get_basename(filename);
	gchar *ch = strrchr(basefilename, '.');
	if (ch)
		*ch = '\0';
	gchar *dirname = g_path_get_dirname(filename);
	FILE *tabfile;
	tabfile = g_fopen(filename,"r");

	gchar *buffer = (gchar *)g_malloc (stats.st_size + 1);
	size_t readsize = fread (buffer, 1, stats.st_size, tabfile);
	fclose (tabfile);
	buffer[readsize] = '\0';	
	
	GArray *array = g_array_sized_new(FALSE,FALSE, sizeof(struct _worditem),20000);
	GArray *array2 = g_array_sized_new(FALSE,FALSE, sizeof(struct _synworditem),20000);
		
	gchar *p, *p1, *p2, *p3, *p4, *p5;
	p = buffer;
	if ((guchar)*p==0xEF && (guchar)*(p+1)==0xBB && (guchar)*(p+2)==0xBF) // UTF-8 order characters.
		p+=3;
	struct _worditem worditem;
	struct _synworditem synworditem;
	gint linenum=1;
	int stripmethod;
	if (strip_html)
		stripmethod = 0;
	else
		stripmethod = 1;
	std::string sametypesequence = "m";
	std::string bookname;
	std::string author;
	std::string email;
	std::string website;
	std::string description;
	std::string date;
	bool print_sameword;
	if (*p == '\n') {
		print_sameword = false;
		p++;
		linenum++;
		while (1) {
			if (*p == '\n') {
				p++;
				linenum++;
				break;
			}
			p++;
			p1 = strchr(p, '\n');
			if (!p1) {
				return;
			}
			*p1 = '\0';
			p1++;
			linenum++;
			if (g_str_has_prefix(p, "stripmethod=")) {
				p += sizeof("stripmethod=") -1;
				if (strcmp(p, "striphtml")==0)
					stripmethod = 0;
				else if (strcmp(p, "stripnewline")==0)
					stripmethod = 1;
				else if (strcmp(p, "keep")==0)
					stripmethod = 2;
			} else if (g_str_has_prefix(p, "sametypesequence=")) {
				p += sizeof("sametypesequence=") -1;
				sametypesequence = p;
			} else if (g_str_has_prefix(p, "bookname=")) {
				p += sizeof("bookname=") -1;
				bookname = p;
			} else if (g_str_has_prefix(p, "author=")) {
				p += sizeof("author=") -1;
				author = p;
			} else if (g_str_has_prefix(p, "email=")) {
				p += sizeof("email=") -1;
				email = p;
			} else if (g_str_has_prefix(p, "website=")) {
				p += sizeof("website=") -1;
				website = p;
			} else if (g_str_has_prefix(p, "date=")) {
				p += sizeof("date=") -1;
				date = p;
			} else if (g_str_has_prefix(p, "description=")) {
				p += sizeof("description=") -1;
				description = p;
			}
			p = p1;
		}
	} else {
		print_sameword = true;
	}
	while (1) {
		if (*p == '\0') {
                        print_info("Over\n");
                        break;
                }
		p1 = strchr(p,'\n');
		if (!p1) {
			gchar *str = g_strdup_printf("Error, no end line 1: %d\n", linenum);
			print_info(str);
			g_free(str);
			return;
		}
		*p1 = '\0';
		p1++;
		linenum++;
		p2 = strchr(p1,'\n');
		if (!p2) {
			gchar *str = g_strdup_printf("Error, no end line 2: %d\n", linenum);
			print_info(str);
			g_free(str);
			return;
		}
		*p2 = '\0';
		p2++;
		linenum++;
		p3=p2;
		if (*p3 != '\n') {
			gchar *str = g_strdup_printf("Error, not null line %d", linenum);
			print_info(str);
			g_free(str);
			return;
		}
		*p3='\0';
		p3++;
		linenum++;
		
		if (stripmethod == 0) {
			html_strstrip(p1, linenum-2, print_info);
		} else if (stripmethod == 1) {
			newline_strstrip(p1, linenum-2, print_info);
		} else if (stripmethod == 2) {
		}
		g_strstrip(p1);
		if (!(*p1)) {
			gchar *str = g_strdup_printf("%s-%d, bad definition!!!\n", basefilename, linenum-1);
			print_info(str);
			g_free(str);
			p= p3;
                        continue;
		}	
		
		p4 = strchr(p, '|');
		if (p4) {
			*p4 = '\0';
			worditem.word = p;
                        g_strstrip(worditem.word);
                        if (!worditem.word[0]) {
				gchar *str = g_strdup_printf("%s-%d, bad word!!!\n", basefilename, linenum-2);
				print_info(str);
				g_free(str);
                                p=p3;
                                continue;
                        }
			worditem.definition = p1;
                        g_array_append_val(array, worditem);
			std::list <std::string> WordList;
			WordList.push_back(worditem.word);
			p4++;
			while (true) {
				p5 = strchr(p4, '|');
				if (p5) {
					*p5 = '\0';
					synworditem.synword = p4;
					g_strstrip(synworditem.synword);
                        		if (!synworditem.synword[0]) {
						gchar *str = g_strdup_printf("%s-%d, bad word!!!\n", basefilename, linenum-2);
						print_info(str);
						g_free(str);
                				p4 = p5+1;
		                                continue;
                		        }
					bool find = false;
					for (std::list<std::string>::const_iterator it=WordList.begin(); it!=WordList.end(); ++it) {
						if (*it == synworditem.synword) {
							find= true;
							break;
						}
					}
					if (find) {
						if (print_sameword) {
							gchar *str = g_strdup_printf("Same word: %s\n", synworditem.synword);
							print_info(str);
							g_free(str);
						}
						p4 = p5+1;
						continue;
					} else {
						WordList.push_back(synworditem.synword);
					}
					synworditem.origword = worditem.word;
					synworditem.definition = worditem.definition;
					g_array_append_val(array2, synworditem);
					p4 = p5+1;
				} else {
					synworditem.synword = p4;
					g_strstrip(synworditem.synword);
                                        if (!synworditem.synword[0]) {
						gchar *str = g_strdup_printf("%s-%d, bad word!!!\n", basefilename, linenum-2);
						print_info(str);
						g_free(str);
                                                break;
                                        }
					bool find = false;
					for (std::list<std::string>::const_iterator it=WordList.begin(); it!=WordList.end(); ++it) {
						if (*it == synworditem.synword) {
							find= true;
							break;
						}
					}
					if (find) {
						if (print_sameword) {
							gchar *str = g_strdup_printf("Same word: %s\n", synworditem.synword);
							print_info(str);
							g_free(str);
						}
						break;
					}
					synworditem.origword = worditem.word;
                                        synworditem.definition = worditem.definition;
                                        g_array_append_val(array2, synworditem);
					break;
				}
			}
		} else {
			worditem.word = p;
			g_strstrip(worditem.word);
			if (!worditem.word[0]) {
				gchar *str = g_strdup_printf("%s-%d, bad word!!!\n", basefilename, linenum-2);
				print_info(str);
				g_free(str);
				p=p3;
				continue;
			}
			worditem.definition = p1;
			g_array_append_val(array, worditem);
		}
		p= p3;
	}		
	g_array_sort(array,comparefunc);
	g_array_sort(array2,comparefunc2);

	gchar ifofilename[256];
	gchar idxfilename[256];
	gchar dicfilename[256];
	sprintf(ifofilename, "%s" G_DIR_SEPARATOR_S "%s.ifo", dirname, basefilename);
	sprintf(idxfilename, "%s" G_DIR_SEPARATOR_S "%s.idx", dirname, basefilename);
	sprintf(dicfilename, "%s" G_DIR_SEPARATOR_S "%s.dict", dirname, basefilename);
	FILE *ifofile = g_fopen(ifofilename,"wb");
	FILE *idxfile = g_fopen(idxfilename,"wb");
	FILE *dicfile = g_fopen(dicfilename,"wb");
	
	guint32 offset_old;
	guint32 tmpglong;
	struct _worditem *pworditem;
	gint definition_len;
	gulong i;
	for (i=0; i< array->len; i++) {
		offset_old = ftell(dicfile);
		pworditem = &g_array_index(array, struct _worditem, i);
		definition_len = strlen(pworditem->definition);
		fwrite(pworditem->definition, 1 ,definition_len,dicfile);
		fwrite(pworditem->word,sizeof(gchar),strlen(pworditem->word)+1,idxfile);
                tmpglong = g_htonl(offset_old);
                fwrite(&(tmpglong),sizeof(guint32),1,idxfile);
                tmpglong = g_htonl(definition_len);
                fwrite(&(tmpglong),sizeof(guint32),1,idxfile);

	}
	fclose(idxfile);
	fclose(dicfile);

	gchar *str = g_strdup_printf("%s wordcount: %d\n", basefilename, array->len);
	print_info(str);
	g_free(str);

	if (array2->len) {
		gchar synfilename[256];
	        sprintf(synfilename, "%s" G_DIR_SEPARATOR_S "%s.syn", dirname, basefilename);
		FILE *synfile = g_fopen(synfilename,"wb");
		struct _synworditem *psynworditem;
		gint iFrom, iTo, iThisIndex, cmpint;
		bool bFound;
		for (i=0; i< array2->len; i++) {
			psynworditem = &g_array_index(array2, struct _synworditem, i);
			fwrite(psynworditem->synword, 1, strlen(psynworditem->synword)+1, synfile);
			bFound=false;
			iFrom=0;
			iTo=array->len-1;
			while (iFrom<=iTo) {
				iThisIndex=(iFrom+iTo)/2;
				pworditem = &g_array_index(array, struct _worditem, iThisIndex);
				cmpint = stardict_strcmp(psynworditem->origword, pworditem->word);
				if (cmpint>0)
					iFrom=iThisIndex+1;
				else if (cmpint<0)
					iTo=iThisIndex-1;
				else {
					bFound=true;
					break;
				}
				
			}
			if (!bFound) {
				gchar *str = g_strdup_printf("Error, %s not find.\n", psynworditem->origword);
				print_info(str);
				g_free(str);
				return;
			}
			do {
				if (iThisIndex==0)
					break;
				pworditem = &g_array_index(array, struct _worditem, iThisIndex-1);
				if (strcmp(psynworditem->origword, pworditem->word)==0)
					iThisIndex--;
				else
					break;
			} while (true);
			bFound=false;
			do {
				pworditem = &g_array_index(array, struct _worditem, iThisIndex);
				if (strcmp(psynworditem->origword, pworditem->word)==0) {
					if (psynworditem->definition == pworditem->definition) {
						bFound=true;
						break;
					} else
						iThisIndex++;
				} else
					break;
			} while (true);
			if (!bFound) {
				gchar *str = g_strdup_printf("Error, %s definition not find.\n", psynworditem->origword);
				print_info(str);
				g_free(str);
                                return;
                        }
			tmpglong = g_htonl(iThisIndex);
	                fwrite(&(tmpglong),sizeof(guint32),1, synfile);
		}
		fclose(synfile);
		gchar *str = g_strdup_printf("%s synwordcount: %d\n", basefilename, array2->len);
		print_info(str);
		g_free(str);
	}
Exemplo n.º 4
0
static void prefs_themes_btn_install_clicked_cb(GtkWidget *widget, gpointer data)
{
	gchar      *filename, *source;
	gchar 	   *themeinfo, *themename;
	gchar      *alert_title = NULL;
	CopyInfo   *cinfo;
	AlertValue  val = 0;
	ThemesData *tdata = prefs_themes_data;

	filename = filesel_select_file_open_folder(_("Select theme folder"), NULL);
	if (filename == NULL) 
		return;

	if (filename[strlen(filename) - 1] != G_DIR_SEPARATOR)
		filename = g_strconcat(filename, G_DIR_SEPARATOR_S, NULL);
	else
		filename = g_strdup(filename);

	cinfo = g_new0(CopyInfo, 1);
	source = g_path_get_dirname(filename);
	themename = g_path_get_basename(source);
	debug_print("Installing '%s' theme from %s\n", themename, filename);

	themeinfo = g_strconcat(source, G_DIR_SEPARATOR_S, THEMEINFO_FILE, NULL);
	alert_title = g_strdup_printf(_("Install theme '%s'"), themename);
	if (file_exist(themeinfo, FALSE) == FALSE) {
		val = alertpanel(alert_title,
				 _("This folder doesn't seem to be a theme folder.\nInstall anyway?"),
				 GTK_STOCK_NO, GTK_STOCK_YES, NULL);
		if (G_ALERTALTERNATE != val)
			goto end_inst;
	}
	if (superuser_p ()) {
		val = alertpanel(alert_title,
				 _("Do you want to install theme for all users?"),
				 GTK_STOCK_NO, GTK_STOCK_YES, NULL);
		switch (val) {
		case G_ALERTALTERNATE:
			cinfo->dest = stock_pixmap_get_system_theme_dir_for_theme(
						themename);
			break;
		case G_ALERTDEFAULT:
			break;
		default:
			goto end_inst;
		}
	}
	g_free(alert_title);
	if (cinfo->dest == NULL) {
		cinfo->dest = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
					  PIXMAP_THEME_DIR, G_DIR_SEPARATOR_S,
					  themename, NULL);
	}
	if (TRUE == is_dir_exist(cinfo->dest)) {
		AlertValue val = alertpanel_full(_("Theme exists"),
				_("A theme with the same name is\nalready installed in this location.\n\n"
				  "Do you want to replace it?"),
				GTK_STOCK_CANCEL, _("Overwrite"), NULL, FALSE,
				NULL, ALERT_WARNING, G_ALERTDEFAULT);
		if (val == G_ALERTALTERNATE) {
			if (remove_dir_recursive(cinfo->dest) < 0) {
				alertpanel_error(_("Couldn't delete the old theme in %s."), cinfo->dest);
				goto end_inst;
			}
		} else {
			goto end_inst;
		}
	}
	if (0 != make_dir_hier(cinfo->dest)) {
		alertpanel_error(_("Couldn't create destination directory %s."), cinfo->dest);
		goto end_inst;
	}
	prefs_themes_foreach_file(source, prefs_themes_file_install, cinfo);
	if (cinfo->status == NULL) {
		GList *insted;

		/* update interface to show newly installed theme */
		prefs_themes_get_themes_and_names(tdata);
		insted = g_list_find_custom(tdata->themes, 
					    (gpointer)(cinfo->dest), 
					    (GCompareFunc)strcmp2);
		if (NULL != insted) {
			alertpanel_notice(_("Theme installed successfully."));
			tdata->displayed = (gchar *)(insted->data);
			prefs_themes_set_themes_menu(GTK_COMBO_BOX(tdata->page->op_menu), tdata);
			prefs_themes_display_global_stats(tdata);
			prefs_themes_get_theme_info(tdata);
		}
		else
			alertpanel_error(_("Failed installing theme"));
	}
	else
		alertpanel_error(_("File %s failed\nwhile installing theme."), cinfo->status);
end_inst:
	g_free(cinfo->dest);
	g_free(filename);
	g_free(source);
	g_free(themeinfo);
	g_free(cinfo);
	g_free(themename);
}
Exemplo n.º 5
0
static pid_t
terminal_execute (TerminalPlugin *term_plugin, const gchar *directory,
				  const gchar *command, gchar **environment)
{
	char **args, **args_ptr;
	GList *args_list, *args_list_ptr;
	gchar *dir;
	VteTerminal *term;
	pid_t pid;
	
	g_return_val_if_fail (command != NULL, 0);
	
	/* Prepare command args */
	args_list = anjuta_util_parse_args_from_string (command);
	args = g_new (char*, g_list_length (args_list) + 1);
	args_list_ptr = args_list;
	args_ptr = args;
	while (args_list_ptr)
	{
		*args_ptr = (char*) args_list_ptr->data;
		args_list_ptr = g_list_next (args_list_ptr);
		args_ptr++;
	}
	*args_ptr = NULL;
	
	if (directory == NULL)
		dir = g_path_get_dirname (args[0]);
	else
		dir = g_strdup (directory);
	
	term = VTE_TERMINAL (term_plugin->term);
	
/*
	vte_terminal_reset (term, TRUE, TRUE);
*/
	
	pid = vte_terminal_fork_command (term, args[0], args,
										environment, dir,
										term_plugin->lastlog,
										term_plugin->update_records,
										term_plugin->update_records);

	/* vte_terminal_form_command return -1 if there is an error */
	if (pid > 0)
	{
		gboolean focus;

		term_plugin->child_pid = pid;

		/* Display terminal widget */
		focus = gtk_widget_is_focus (term_plugin->shell);
		gtk_container_remove (GTK_CONTAINER (term_plugin->frame), term_plugin->shell_box);
		gtk_container_add (GTK_CONTAINER (term_plugin->frame), term_plugin->term_box);
		gtk_widget_show_all (term_plugin->term_box);
		if (focus)
			gtk_widget_grab_focus (term_plugin->term);

		if (term_plugin->widget_added_to_shell)
			anjuta_shell_present_widget (ANJUTA_PLUGIN (term_plugin)->shell,
									 term_plugin->frame, NULL);
	}

	g_free (dir);
	g_free (args);
	g_list_foreach (args_list, (GFunc)g_free, NULL);
	g_list_free (args_list);

	return pid;
}
/**
 * grub_choose_default_exec:
 * #directory   : the directory to search the script in
 * #script      : the file we should try to execute
 *
 * Searches in directory for script or script* and tries to execute it.
 */
gboolean
grub_choose_default_exec(const gchar * directory, const gchar * script, gboolean sync, GError **error)
{
  gchar * path;
#ifdef G_OS_WIN32
  GDir * dir;
  const gchar * fn;
  gchar * dirname, * basename;
#endif

  g_assert (error == NULL || *error == NULL);

  path = g_build_filename (directory, script, NULL);

#ifdef G_OS_WIN32
  dirname = g_path_get_dirname (path);
  basename = g_path_get_basename (path);
  g_free (path);

  dir = g_dir_open (dirname, 0, NULL);

  if (dir == NULL)
  {
    g_set_error (error, GCHD_ERROR,
                 GCHD_ERROR_FILE_NOT_FOUND,
                 "Could not find or open %s", dirname);
    return FALSE;
  }

  while ((fn = g_dir_read_name (dir)) != NULL)
  {
    DBG ("Considering file %s", fn);
    if (g_str_has_prefix (fn, basename))
    {
      DBG (" -> has prefix %s", basename);
      path = g_build_filename (dirname, fn, NULL);

      break;
    }
  }
  g_dir_close (dir);
#endif

  g_print ("Trying to execute with prefix %s\n", path);

  if (g_file_test (path, G_FILE_TEST_IS_EXECUTABLE))
  {
    gchar *argv[3];
    gboolean r;

#ifdef G_OS_WIN32
    if (g_str_has_suffix (path, ".vbs"))
    {
      argv[0] = "cscript.exe";
      argv[1] = path;
      argv[2] = NULL;
    }
    else
#endif
    {
      argv[0] = path;
      argv[1] = NULL;
    }

    if (sync) {
      r = g_spawn_sync (NULL,
                        argv,
                        NULL,
                        G_SPAWN_SEARCH_PATH,
                        NULL,
                        NULL,
                        NULL,
                        NULL, 
                        NULL, 
                        error);
    } else {
      r = g_spawn_async (NULL,
                         argv,
                         NULL,
                         G_SPAWN_SEARCH_PATH,
                         NULL,
                         NULL,
                         NULL,
                         error);
    }

    g_free (path);
    return r;
  }

  g_free (path);
  g_set_error (error, GCHD_ERROR,
                GCHD_ERROR_FILE_NOT_FOUND,
                "Could not find a script %s in %s", script, directory);
  return FALSE;
}
Exemplo n.º 7
0
static int
open_logfile(logger_t* logger)
{
    // maybe run the filename through strftime
    if (logger->use_strftime) {
        char new_prefix[PATH_MAX];
        time_t now = time (NULL);
        strftime(new_prefix, sizeof(new_prefix),
                logger->input_fname, localtime(&now));

        // If auto-increment is enabled and the strftime-formatted filename
        // prefix has changed, then reset the auto-increment counter.
        if(logger->auto_increment && strcmp(new_prefix, logger->fname_prefix))
            logger->next_increment_num = 0;
        strcpy(logger->fname_prefix, new_prefix);
    } else {
        strcpy(logger->fname_prefix, logger->input_fname);
    }

    if (logger->auto_increment) {
        /* Loop through possible file names until we find one that doesn't
         * already exist.  This way, we never overwrite an existing file. */
        do {
            snprintf(logger->fname, sizeof(logger->fname), "%s.%02d",
                    logger->fname_prefix, logger->next_increment_num);
            logger->next_increment_num++;
        } while(g_file_test(logger->fname, G_FILE_TEST_EXISTS));

        if (errno != ENOENT) {
            perror ("Error: checking for previous logs");
            return 1;
        }
    } else {
        strcpy(logger->fname, logger->fname_prefix);
        if (! logger->force_overwrite) {
            if (g_file_test(logger->fname, G_FILE_TEST_EXISTS))
            {
                fprintf (stderr, "Refusing to overwrite existing file \"%s\"\n",
                        logger->fname);
                return 1;
            }
        }
    }

    // create directories if needed
    char *dirpart = g_path_get_dirname (logger->fname);
    if (! g_file_test (dirpart, G_FILE_TEST_IS_DIR)) {
        mkdir_with_parents (dirpart, 0755);
    }
    g_free (dirpart);

    fprintf (stderr, "Opening log file \"%s\"\n", logger->fname);

    // open output file
    logger->log = lcm_eventlog_create(logger->fname, "w");
    if (logger->log == NULL) {
        perror ("Error: fopen failed");
        return 1;
    }
    return 0;
}
Exemplo n.º 8
0
int main(int argc, char *arg[])
{
  bindtextdomain (GETTEXT_PACKAGE, DARKTABLE_LOCALEDIR);
  bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
  textdomain (GETTEXT_PACKAGE);

  gtk_init (&argc, &arg);

  // parse command line arguments

  char *image_filename = NULL;
  char *xmp_filename = NULL;
  char *output_filename = NULL;
  int file_counter = 0;
  int width = 0, height = 0, bpp = 0;
  gboolean verbose = FALSE, high_quality = TRUE;

  for(int k=1; k<argc; k++)
  {
    if(arg[k][0] == '-')
    {
      if(!strcmp(arg[k], "--help"))
      {
        usage(arg[0]);
        exit(1);
      }
      else if(!strcmp(arg[k], "--version"))
      {
        printf("this is darktable-cli\ncopyright (c) 2012 johannes hanika, tobias ellinghaus\n");
        exit(1);
      }
      else if(!strcmp(arg[k], "--width"))
      {
        k++;
        width = MAX(atoi(arg[k]), 0);
      }
      else if(!strcmp(arg[k], "--height"))
      {
        k++;
        height = MAX(atoi(arg[k]), 0);
      }
      else if(!strcmp(arg[k], "--bpp"))
      {
        k++;
        bpp = MAX(atoi(arg[k]), 0);
        fprintf(stderr, "%s %d\n", _("TODO: sorry, due to api restrictions we currently cannot set the bpp to"), bpp);
      }
      else if(!strcmp(arg[k], "--hq"))
      {
        k++;
        gchar *str = g_ascii_strup(arg[k], -1);
        if(!g_strcmp0(str, "0") || !g_strcmp0(str, "FALSE"))
          high_quality = FALSE;
        else if(!g_strcmp0(str, "1") || !g_strcmp0(str, "TRUE"))
          high_quality = TRUE;
        else
        {
          fprintf(stderr, "%s: %s\n", _("Unknown option for --hq"), arg[k]);
          usage(arg[0]);
          exit(1);
        }
        g_free(str);
      }
      else if(!strcmp(arg[k], "-v") || !strcmp(arg[k], "--verbose"))
      {
        verbose = TRUE;
      }

    }
    else
    {
      if(file_counter == 0)
        image_filename = arg[k];
      else if(file_counter == 1)
        xmp_filename = arg[k];
      else if(file_counter == 2)
        output_filename = arg[k];
      file_counter++;
    }
  }

  if(file_counter < 2 || file_counter > 3)
  {
    usage(arg[0]);
    exit(1);
  }
  else if(file_counter == 2)
  {
    // no xmp file given
    output_filename = xmp_filename;
    xmp_filename = NULL;
  }

  // the output file already exists, so there will be a sequence number added
  if(g_file_test(output_filename, G_FILE_TEST_EXISTS))
  {
    fprintf(stderr, "%s\n", _("output file already exists, it will get renamed"));
  }

  char *m_arg[] = {"darktable-cli", "--library", ":memory:", NULL};
  // init dt without gui:
  if(dt_init(3, m_arg, 0)) exit(1);

  dt_film_t film;
  int id = 0;
  int filmid = 0;

  gchar *directory = g_path_get_dirname(image_filename);
  filmid = dt_film_new(&film, directory);
  id = dt_image_import(filmid, image_filename, TRUE);
  if(!id)
  {
    fprintf(stderr, _("error: can't open file %s"), image_filename);
    fprintf(stderr, "\n");
    exit(1);
  }
  g_free(directory);

  // attach xmp, if requested:
  if(xmp_filename)
  {
    const dt_image_t *cimg = dt_image_cache_read_get(darktable.image_cache, id);
    dt_image_t *image = dt_image_cache_write_get(darktable.image_cache, cimg);
    dt_exif_xmp_read(image, xmp_filename, 1);
    // don't write new xmp:
    dt_image_cache_write_release(darktable.image_cache, image, DT_IMAGE_CACHE_RELAXED);
    dt_image_cache_read_release(darktable.image_cache, image);
  }

  // print the history stack
  if(verbose)
  {
    gchar *history = dt_history_get_items_as_string(id);
    if(history)
      printf("%s\n", history);
    else
      printf("[%s]\n", _("empty history stack"));
  }

  // try to find out the export format from the output_filename
  char *ext = output_filename + strlen(output_filename);
  while(ext > output_filename && *ext != '.') ext--;
  *ext = '\0';
  ext++;

  if(!strcmp(ext, "jpg"))
    ext = "jpeg";

  // init the export data structures
  int size = 0, dat_size = 0;
  dt_imageio_module_format_t *format;
  dt_imageio_module_storage_t *storage;
  dt_imageio_module_data_t *sdata, *fdata;

  storage = dt_imageio_get_storage_by_name("disk"); // only exporting to disk makes sense
  if(storage == NULL)
  {
    fprintf(stderr, "%s\n", _("cannot find disk storage module. please check your installation, something seems to be broken."));
    exit(1);
  }

  sdata = storage->get_params(storage, &size);
  if(sdata == NULL)
  {
    fprintf(stderr, "%s\n", _("failed to get parameters from storage module, aborting export ..."));
    exit(1);
  }

  // and now for the really ugly hacks. don't tell your children about this one or they won't sleep at night any longer ...
  g_strlcpy((char*)sdata, output_filename, DT_MAX_PATH_LEN);
  // all is good now, the last line didn't happen.

  format = dt_imageio_get_format_by_name(ext);
  if(format == NULL)
  {
    fprintf(stderr, _("unknown extension '.%s'"), ext);
    fprintf(stderr, "\n");
    exit(1);
  }

  fdata = format->get_params(format, &dat_size);
  if(fdata == NULL)
  {
    fprintf(stderr, "%s\n", _("failed to get parameters from format module, aborting export ..."));
    exit(1);
  }

  uint32_t w,h,fw,fh,sw,sh;
  fw=fh=sw=sh=0;
  storage->dimension(storage, &sw, &sh);
  format->dimension(format, &fw, &fh);

  if( sw==0 || fw==0) w=sw>fw?sw:fw;
  else w=sw<fw?sw:fw;

  if( sh==0 || fh==0) h=sh>fh?sh:fh;
  else h=sh<fh?sh:fh;

  fdata->max_width  = width;
  fdata->max_height = height;
  fdata->max_width = (w!=0 && fdata->max_width >w)?w:fdata->max_width;
  fdata->max_height = (h!=0 && fdata->max_height >h)?h:fdata->max_height;
  fdata->style[0] = '\0';

  //TODO: add a callback to set the bpp without going through the config

  storage->store(sdata, id, format, fdata, 1, 1, high_quality);

  // cleanup time
  if(storage->finalize_store) storage->finalize_store(storage, sdata);
  storage->free_params(storage, sdata);
  format->free_params(format, fdata);

  dt_cleanup();
}
Exemplo n.º 9
0
gboolean maki_dcc_send_resume_accept (makiDCCSend* dcc, const gchar* filename, guint16 port, goffset position, guint32 token, gboolean is_incoming)
{
	g_return_val_if_fail(dcc != NULL, FALSE);

	if (dcc->status & s_incoming)
	{
		gchar* basename;
		gchar* dirname;

		if (!is_incoming)
		{
			return FALSE;
		}

		basename = g_path_get_basename(dcc->path);

		if (strcmp(basename, filename) != 0)
		{
			g_free(basename);
			return FALSE;
		}

		g_free(basename);

		if (dcc->port != port)
		{
			return FALSE;
		}

		if (dcc->d.in.accept || !dcc->d.in.resume)
		{
			return FALSE;
		}

		dirname = g_path_get_dirname(dcc->path);
		g_mkdir_with_parents(dirname, 0777);
		g_free(dirname);

		if ((dcc->channel.file = g_io_channel_new_file(dcc->path, "r+", NULL)) == NULL)
		{
			return FALSE;
		}

		g_io_channel_set_close_on_unref(dcc->channel.file, TRUE);
		g_io_channel_set_encoding(dcc->channel.file, NULL, NULL);
		g_io_channel_set_buffered(dcc->channel.file, FALSE);

		if (g_io_channel_seek_position(dcc->channel.file, position, G_SEEK_SET, NULL) != G_IO_STATUS_NORMAL)
		{
			return FALSE;
		}

		dcc->position = position;
		dcc->resume = position;

		dcc->status &= ~s_resumable;
		dcc->status |= s_resumed;

		maki_dcc_send_emit(dcc);

		maki_dcc_send_accept(dcc);
	}
	else
	{
		gchar* basename;

		if (is_incoming)
		{
			return FALSE;
		}

		basename = g_path_get_basename(dcc->path);

		if (strcmp(basename, filename) != 0)
		{
			g_free(basename);
			return FALSE;
		}

		g_free(basename);

		if (dcc->port != port)
		{
			return FALSE;
		}

		if (g_io_channel_seek_position(dcc->channel.file, position, G_SEEK_SET, NULL) != G_IO_STATUS_NORMAL)
		{
			return FALSE;
		}

		dcc->position = position;
		dcc->resume = position;
		dcc->d.out.ack.position = position;

		dcc->status &= ~s_resumable;
		dcc->status |= s_resumed;

		maki_dcc_send_emit(dcc);
	}

	return TRUE;
}
Exemplo n.º 10
0
/*! \brief Save the schematic file
 *  \par Function Description
 *  This function saves the current schematic file in the toplevel object.
 *
 *  \param [in,out] toplevel  The TOPLEVEL object containing the schematic.
 *  \param [in]      filename  The file name to save the schematic to.
 *  \return 1 on success, 0 on failure.
 */
int f_save(TOPLEVEL *toplevel, const char *filename)
{
  gchar *backup_filename;
  gchar *real_filename;
  gchar *only_filename;
  gchar *dirname;
  mode_t saved_umask, mask;
  struct stat st;

  /* Get the real filename and file permissions */
  real_filename = follow_symlinks (filename, NULL);

  if (real_filename == NULL) {
    s_log_message (_("Can't get the real filename of %s."), filename);
    return 0;
  }
  
  /* Get the directory in which the real filename lives */
  dirname = g_path_get_dirname (real_filename);
  only_filename = g_path_get_basename(real_filename);  

  /* Do a backup if it's not an undo file backup and it was never saved. */
  if (toplevel->page_current->saved_since_first_loaded == 0) {
    if ( (g_file_test (real_filename, G_FILE_TEST_EXISTS)) && 
	 (!g_file_test(real_filename, G_FILE_TEST_IS_DIR)) )
    {
      backup_filename = g_strdup_printf("%s%c%s~", dirname, 
					G_DIR_SEPARATOR, only_filename);

      /* Make the backup file read-write before saving a new one */
      if ( g_file_test (backup_filename, G_FILE_TEST_EXISTS) && 
	   (! g_file_test (backup_filename, G_FILE_TEST_IS_DIR))) {
	if (chmod(backup_filename, S_IREAD|S_IWRITE) != 0) {
	  s_log_message (_("Could NOT set previous backup file [%s] read-write\n"),
			 backup_filename);
	}
      }
	
      if (rename(real_filename, backup_filename) != 0) {
	s_log_message (_("Can't save backup file: %s."), backup_filename);
      }
      else {
	/* Make the backup file readonly so a 'rm *' command will ask 
	   the user before deleting it */
	saved_umask = umask(0);
	mask = (S_IWRITE|S_IWGRP|S_IEXEC|S_IXGRP|S_IXOTH);
	mask = (~mask)&0777;
	mask &= ((~saved_umask) & 0777);
	if (chmod(backup_filename, mask) != 0) {
	  s_log_message (_("Could NOT set backup file [%s] readonly\n"),
                         backup_filename);
	}
	umask(saved_umask);
      }

      g_free(backup_filename);
    }
  }
    /* If there is not an existing file with that name, compute the
     * permissions and uid/gid that we will use for the newly-created file.
     */
       
  if (stat (real_filename, &st) != 0)
  {
    struct stat dir_st;
    int result;
    
    /* Use default permissions */
    saved_umask = umask(0);
    st.st_mode = 0666 & ~saved_umask;
    umask(saved_umask);
#ifdef HAVE_CHOWN
    st.st_uid = getuid ();
    
    result = stat (dirname, &dir_st);
    
    if (result == 0 && (dir_st.st_mode & S_ISGID))
	  st.st_gid = dir_st.st_gid;
    else
    st.st_gid = getgid ();
#endif /* HAVE_CHOWN */
  }
  g_free (dirname);
  g_free (only_filename);
  
  if (o_save(toplevel, real_filename)) {

    toplevel->page_current->saved_since_first_loaded = 1;

    /* Reset the last saved timer */
    g_get_current_time (&toplevel->page_current->last_load_or_save_time);
    toplevel->page_current->ops_since_last_backup = 0;
    toplevel->page_current->do_autosave_backup = 0;

    /* Restore permissions. */
    chmod (real_filename, st.st_mode);
#ifdef HAVE_CHOWN
    if (chown (real_filename, st.st_uid, st.st_gid)) {
      /* Error occured with chown */
#warning FIXME: What do we do?
    }
#endif

    g_free (real_filename);
    return 1;
  }
  else {
    g_free (real_filename);
    return 0;
  }
}
Exemplo n.º 11
0
/*! \brief Follow symlinks until a real file is found
 *  \par Function Description
 *  Does readlink() recursively until we find a real filename.
 *
 *  \param [in]     filename  The filename to search for.
 *  \param [in,out] err       #GError structure for error reporting,
 *                            or NULL to disable error reporting.
 *  \return The newly-allocated path to real file on success, NULL
 *          otherwise.
 *
 *  \note Originally taken from gedit's source code.
 */
char *follow_symlinks (const gchar *filename, GError **err)
{
  gchar *followed_filename = NULL;
  gint link_count = 0;
  GError *tmp_err = NULL;

  if (filename == NULL) {
    g_set_error (err, G_FILE_ERROR, G_FILE_ERROR_INVAL,
                 "%s", g_strerror (EINVAL));
    return NULL;
  }

  if (strlen (filename) + 1 > MAXPATHLEN) {
    g_set_error (err, G_FILE_ERROR, G_FILE_ERROR_NAMETOOLONG,
                 "%s", g_strerror (ENAMETOOLONG));
    return NULL;
  }

  followed_filename = g_strdup (filename);

#ifdef __MINGW32__
  /* MinGW does not have symlinks */
  return followed_filename;
#else

  while (link_count < MAX_LINK_LEVEL) {
    struct stat st;
    gchar *linkname = NULL;

    if (lstat (followed_filename, &st) != 0) {
      /* We could not access the file, so perhaps it does not
       * exist.  Return this as a real name so that we can
       * attempt to create the file.
       */
      return followed_filename;
    }

    if (!S_ISLNK (st.st_mode)) {
      /* It's not a link, so we've found what we're looking for! */
      return followed_filename;
    }

    link_count++;

    linkname = g_file_read_link (followed_filename, &tmp_err);

    if (linkname == NULL) {
      g_propagate_error(err, tmp_err);
      g_free (followed_filename);
      return NULL;
    }

    /* If the linkname is not an absolute path name, append
     * it to the directory name of the followed filename.  E.g.
     * we may have /foo/bar/baz.lnk -> eek.txt, which really
     * is /foo/bar/eek.txt.
     */

    if (!g_path_is_absolute(linkname)) {
      gchar *dirname = NULL;
      gchar *tmp = NULL;

      dirname = g_path_get_dirname(followed_filename);

      tmp = g_build_filename (dirname, linkname, NULL);
      g_free (followed_filename);
      g_free (dirname);
      g_free (linkname);
      followed_filename = tmp;
    } else {
      g_free (followed_filename);
      followed_filename = linkname;
    }
  }

  /* Too many symlinks */
  g_set_error (err, G_FILE_ERROR, G_FILE_ERROR_LOOP,
               _("%s: %s"), g_strerror (EMLINK), followed_filename);
  g_free (followed_filename);
  return NULL;

#endif /* __MINGW32__ */
}
Exemplo n.º 12
0
static void
mex_search_plugin_update_history (MexSearchPlugin *self,
                                  const gchar     *term)
{
  gint i;
  gsize length;
  gchar *contents, *current;

  MexSearchPluginPrivate *priv = self->priv;
  const gchar *base_dir =
    mex_settings_get_config_dir (mex_settings_get_default ());
  gchar *history_file = g_build_filename (base_dir, "search", "history", NULL);

  /* Read the history file contents */
  /* TODO: Make this less rubbish? */
  g_file_get_contents (history_file, &contents, &length, NULL);

  /* Prepend new search-term if appropriate */
  if (term)
    {
      gint terms;
      gchar *path;
      gsize new_length;

      gsize term_len = strlen (term);
      gchar *new_contents = g_malloc (length + term_len + 1);

      memcpy (new_contents, term, term_len);
      new_contents[term_len] = '\n';
      new_length = term_len + 1;

      /* Truncate list to 10 terms and remove duplicates */
      if (contents)
        {
          i = 0;
          terms = 1;
          do
            {
              gint cur_len;
              char *eos = strchr (contents + i, '\n');

              if (!eos)
                cur_len = strlen (contents + i);
              else
                cur_len = eos - (contents + i);

              if ((cur_len != term_len) ||
                  (strncmp (contents + i, term, term_len) != 0))
                {
                  memcpy (new_contents + new_length, contents + i, cur_len + 1);
                  new_length += cur_len + 1;

                  if (++terms >= 10)
                    break;
                }

              if (!eos)
                break;

              i += cur_len + 1;
            } while (i < length);
        }

      new_contents[new_length++] = '\0';

      /* Save new list */
      path = g_path_get_dirname (history_file);
      g_mkdir_with_parents (path, 0755);
      g_free (path);

      g_file_set_contents (history_file, new_contents, new_length, NULL);

      /* Replace content with new content */
      g_free (contents);
      contents = new_contents;
      length = new_length;
    }

  /* Empty current list */
  mex_model_clear (MEX_MODEL (priv->history_model));

  /* Populate with search history */
  if (contents)
    {
      current = contents;
      while (current < contents + length)
        {
          MexContent *content =
            MEX_CONTENT (mex_program_new (priv->history_model));
          gchar *end = g_utf8_strchr (current, -1, '\n');

          if (end)
            *end = '\0';

          if (*current)
            {
              mex_content_set_metadata (content,
                                        MEX_CONTENT_METADATA_TITLE,
                                        current);
              mex_content_set_metadata (content,
                                        MEX_CONTENT_METADATA_MIMETYPE,
                                        "x-mex/search");
              mex_model_add_content (MEX_MODEL (priv->history_model),
                                     content);
            }

          if (end)
            current = end + 1;
          else
            break;
        }

      g_free (contents);
    }
}
Exemplo n.º 13
0
Plugin::Plugin( GModule * _module , const GPointerMap & _symbols )
:
    module( _module ),
    symbols( _symbols )
{
	g_assert( module );

	TPPluginInitialize initialize = ( TPPluginInitialize ) get_symbol( TP_PLUGIN_INITIALIZE );

	shutdown = ( TPPluginShutdown ) get_symbol( TP_PLUGIN_SHUTDOWN );

	g_assert( initialize );
	g_assert( shutdown );

	// Load the configuration file for this plugin, if it exists

	gchar * config = 0;

	if ( const gchar * file_name = g_module_name( module ) )
	{
		gchar * base_name = g_path_get_basename( file_name );

		if ( gchar * dot = g_strrstr( base_name , "." ) )
		{
			gchar * dir_name = g_path_get_dirname( file_name );

			String config_file_name;

			config_file_name = dir_name;
			config_file_name += G_DIR_SEPARATOR_S;
			config_file_name += String( base_name , dot - base_name );
			config_file_name += ".config";

			if ( g_file_get_contents( config_file_name.c_str() , & config , 0 , 0 ) )
			{
				tplog2( "  CONFIG LOADED" );
			}
			else
			{
				config = 0;
			}

			g_free( dir_name );
		}

		g_free( base_name );
	}

	// Now call its initialize function

	memset( & info , 0 , sizeof( info ) );

	tplog2( "  INITIALIZING..." );

	initialize( & info , config );

	g_free( config );

	tplog2( "  INITIALIZED" );

	info.name[ sizeof( info.name ) - 1 ] = 0;
	info.version[ sizeof( info.version ) - 1 ] = 0;

	tplog( "  NAME        : %s" , info.name );
	tplog( "  VERSION     : %s" , info.version );
	tplog( "  RESIDENT    : %s" , info.resident ? "YES" : "NO" );
	tplog( "  USER DATA   : %p" , info.user_data );

	if ( info.resident )
	{
		g_module_make_resident( module );
	}
}
Exemplo n.º 14
0
int
main (int argc, char **argv)
{
  GError *error;
  GHashTable *table;
  gchar *srcfile;
  gchar *target = NULL;
  gchar *binary_target = NULL;
  gboolean generate_automatic = FALSE;
  gboolean generate_source = FALSE;
  gboolean generate_header = FALSE;
  gboolean manual_register = FALSE;
  gboolean generate_dependencies = FALSE;
  char *c_name = NULL;
  char *c_name_no_underscores;
  GOptionContext *context;
  GOptionEntry entries[] = {
    { "target", 0, 0, G_OPTION_ARG_FILENAME, &target, N_("name of the output file"), N_("FILE") },
    { "sourcedir", 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &sourcedirs, N_("The directories where files are to be read from (default to current directory)"), N_("DIRECTORY") },
    { "generate", 0, 0, G_OPTION_ARG_NONE, &generate_automatic, N_("Generate output in the format selected for by the target filename extension"), NULL },
    { "generate-header", 0, 0, G_OPTION_ARG_NONE, &generate_header, N_("Generate source header"), NULL },
    { "generate-source", 0, 0, G_OPTION_ARG_NONE, &generate_source, N_("Generate sourcecode used to link in the resource file into your code"), NULL },
    { "generate-dependencies", 0, 0, G_OPTION_ARG_NONE, &generate_dependencies, N_("Generate dependency list"), NULL },
    { "manual-register", 0, 0, G_OPTION_ARG_NONE, &manual_register, N_("Don't automatically create and register resource"), NULL },
    { "c-name", 0, 0, G_OPTION_ARG_STRING, &c_name, N_("C identifier name used for the generated source code"), NULL },
    { NULL }
  };

#ifdef G_OS_WIN32
  extern gchar *_glib_get_locale_dir (void);
  gchar *tmp;
#endif

  setlocale (LC_ALL, "");
  textdomain (GETTEXT_PACKAGE);

#ifdef G_OS_WIN32
  tmp = _glib_get_locale_dir ();
  bindtextdomain (GETTEXT_PACKAGE, tmp);
  g_free (tmp);
#else
  bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
#endif

#ifdef HAVE_BIND_TEXTDOMAIN_CODESET
  bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
#endif

  g_type_init ();

  context = g_option_context_new (N_("FILE"));
  g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
  g_option_context_set_summary (context,
    N_("Compile a resource specification into a resource file.\n"
       "Resource specification files have the extension .gresource.xml,\n"
       "and the resource file have the extension called .gresource."));
  g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);

  error = NULL;
  if (!g_option_context_parse (context, &argc, &argv, &error))
    {
      g_printerr ("%s\n", error->message);
      return 1;
    }

  g_option_context_free (context);

  if (argc != 2)
    {
      g_printerr (_("You should give exactly one file name\n"));
      return 1;
    }

  srcfile = argv[1];

  xmllint = g_strdup (g_getenv ("XMLLINT"));
  if (xmllint == NULL)
    xmllint = g_find_program_in_path ("xmllint");
  if (xmllint == NULL)
    g_printerr ("XMLLINT not set and xmllint not found in path; skipping xml preprocessing.\n");

  gdk_pixbuf_pixdata = g_strdup (g_getenv ("GDK_PIXBUF_PIXDATA"));
  if (gdk_pixbuf_pixdata == NULL)
    gdk_pixbuf_pixdata = g_find_program_in_path ("gdk-pixbuf-pixdata");

  if (target == NULL)
    {
      char *dirname = g_path_get_dirname (srcfile);
      char *base = g_path_get_basename (srcfile);
      char *target_basename;
      if (g_str_has_suffix (base, ".xml"))
	base[strlen(base) - strlen (".xml")] = 0;

      if (generate_source)
	{
	  if (g_str_has_suffix (base, ".gresource"))
	    base[strlen(base) - strlen (".gresource")] = 0;
	  target_basename = g_strconcat (base, ".c", NULL);
	}
      else
	{
	  if (g_str_has_suffix (base, ".gresource"))
	    target_basename = g_strdup (base);
	  else
	    target_basename = g_strconcat (base, ".gresource", NULL);
	}

      target = g_build_filename (dirname, target_basename, NULL);
      g_free (target_basename);
      g_free (dirname);
      g_free (base);
    }
  else if (generate_automatic)
    {
      if (g_str_has_suffix (target, ".c"))
        generate_source = TRUE;
      else if (g_str_has_suffix (target, ".h"))
        generate_header = TRUE;
      else if (g_str_has_suffix (target, ".gresource"))
        ;
    }

  if ((table = parse_resource_file (srcfile, !generate_dependencies)) == NULL)
    {
      g_free (target);
      return 1;
    }

  if (generate_dependencies)
    {
      GHashTableIter iter;
      gpointer key, data;
      FileData *file_data;

      g_hash_table_iter_init (&iter, table);
      while (g_hash_table_iter_next (&iter, &key, &data))
        {
          file_data = data;
          g_print ("%s\n",file_data->filename);
        }
    }
  else if (generate_source || generate_header)
    {
      if (generate_source)
	{
	  int fd = g_file_open_tmp (NULL, &binary_target, NULL);
	  if (fd == -1)
	    {
	      g_printerr ("Can't open temp file\n");
	      return 1;
	    }
	  close (fd);
	}

      if (c_name == NULL)
	{
	  char *base = g_path_get_basename (srcfile);
	  GString *s;
	  char *dot;
	  int i;

	  /* Remove extensions */
	  dot = strchr (base, '.');
	  if (dot)
	    *dot = 0;

	  s = g_string_new ("");

	  for (i = 0; base[i] != 0; i++)
	    {
	      const char *first = G_CSET_A_2_Z G_CSET_a_2_z "_";
	      const char *rest = G_CSET_A_2_Z G_CSET_a_2_z G_CSET_DIGITS "_";
	      if (strchr ((i == 0) ? first : rest, base[i]) != NULL)
		g_string_append_c (s, base[i]);
	      else if (base[i] == '-')
		g_string_append_c (s, '_');

	    }

	  c_name = g_string_free (s, FALSE);
	}
    }
  else
    binary_target = g_strdup (target);

  c_name_no_underscores = c_name;
  while (c_name_no_underscores && *c_name_no_underscores == '_')
    c_name_no_underscores++;

  if (binary_target != NULL &&
      !write_to_file (table, binary_target, &error))
    {
      g_printerr ("%s\n", error->message);
      g_free (target);
      return 1;
    }

  if (generate_header)
    {
      FILE *file;

      file = fopen (target, "w");
      if (file == NULL)
	{
	  g_printerr ("can't write to file %s", target);
	  return 1;
	}

      fprintf (file,
	       "#ifndef __RESOURCE_%s_H__\n"
	       "#define __RESOURCE_%s_H__\n"
	       "\n"
	       "#include <gio/gio.h>\n"
	       "\n"
	       "extern GResource *%s_get_resource (void);\n",
	       c_name, c_name, c_name);

      if (manual_register)
	fprintf (file,
		 "\n"
		 "extern void %s_register_resource (void);\n"
		 "extern void %s_unregister_resource (void);\n"
		 "\n",
		 c_name, c_name);

      fprintf (file,
	       "#endif\n");

      fclose (file);
    }
  else if (generate_source)
    {
      FILE *file;
      guint8 *data;
      gsize data_size;
      gsize i;

      if (!g_file_get_contents (binary_target, (char **)&data,
				&data_size, NULL))
	{
	  g_printerr ("can't read back temporary file");
	  return 1;
	}
      g_unlink (binary_target);

      file = fopen (target, "w");
      if (file == NULL)
	{
	  g_printerr ("can't write to file %s", target);
	  return 1;
	}

      fprintf (file,
	       "#include <gio/gio.h>\n"
	       "\n"
	       "#if defined (__ELF__) && ( __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 6))\n"
	       "# define SECTION __attribute__ ((section (\".gresource.%s\"), aligned (8)))\n"
	       "#else\n"
	       "# define SECTION\n"
	       "#endif\n"
	       "\n"
	       "static const SECTION union { const guint8 data[%"G_GSIZE_FORMAT"]; const double alignment; void * const ptr;}  %s_resource_data = { {\n",
	       c_name_no_underscores, data_size, c_name);

      for (i = 0; i < data_size; i++) {
	if (i % 8 == 0)
	  fprintf (file, "  ");
	fprintf (file, "0x%2.2x", (int)data[i]);
	if (i != data_size - 1)
	  fprintf (file, ", ");
	if ((i % 8 == 7) || (i == data_size - 1))
	  fprintf (file, "\n");
      }

      fprintf (file, "} };\n");

      fprintf (file,
	       "\n"
	       "static GStaticResource static_resource = { %s_resource_data.data, sizeof (%s_resource_data.data) };\n"
	       "extern GResource *%s_get_resource (void);\n"
	       "GResource *%s_get_resource (void)\n"
	       "{\n"
	       "  return g_static_resource_get_resource (&static_resource);\n"
	       "}\n",
	       c_name, c_name, c_name, c_name);


      if (manual_register)
	{
	  fprintf (file,
		   "\n"
		   "extern void %s_unregister_resource (void);\n"
		   "void %s_unregister_resource (void)\n"
		   "{\n"
		   "  g_static_resource_fini (&static_resource);\n"
		   "}\n"
		   "\n"
		   "extern void %s_register_resource (void);\n"
		   "void %s_register_resource (void)\n"
		   "{\n"
		   "  g_static_resource_init (&static_resource);\n"
		   "}\n",
		   c_name, c_name, c_name, c_name);
	}
      else
	{
	  fprintf (file, "%s", gconstructor_code);
	  fprintf (file,
		   "\n"
		   "#ifdef G_HAS_CONSTRUCTORS\n"
		   "\n"
		   "#ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA\n"
		   "#pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(resource_constructor)\n"
		   "#endif\n"
		   "G_DEFINE_CONSTRUCTOR(resource_constructor)\n"
		   "#ifdef G_DEFINE_DESTRUCTOR_NEEDS_PRAGMA\n"
		   "#pragma G_DEFINE_DESTRUCTOR_PRAGMA_ARGS(resource_destructor)\n"
		   "#endif\n"
		   "G_DEFINE_DESTRUCTOR(resource_destructor)\n"
		   "\n"
		   "#else\n"
		   "#warning \"Constructor not supported on this compiler, linking in resources will not work\"\n"
		   "#endif\n"
		   "\n"
		   "static void resource_constructor (void)\n"
		   "{\n"
		   "  g_static_resource_init (&static_resource);\n"
		   "}\n"
		   "\n"
		   "static void resource_destructor (void)\n"
		   "{\n"
		   "  g_static_resource_fini (&static_resource);\n"
		   "}\n");
	}

      fclose (file);

      g_free (data);
    }

  g_free (binary_target);
  g_free (target);
  g_hash_table_destroy (table);
  g_free (xmllint);

  return 0;
}
Exemplo n.º 15
0
int main(int argc, char** argv)
{
    GOptionContext* opt_ctx;
    GError* err = NULL;
    GMenuTree* menu_tree = NULL;
    GMenuTreeDirectory* root_dir;
    GSList* l;
    FILE *of;
    int ofd;
    char *tmp;
    char *dir;
    const gchar* const * xdg_cfg_dirs;
    const gchar* const * pdir;
    const char* menu_prefix;
    char* menu_file;
    char* plus_ptr = NULL;

    setlocale (LC_ALL, "");

    opt_ctx = g_option_context_new("Generate cache for freedesktop.org compliant menus.");
    g_option_context_add_main_entries( opt_ctx, opt_entries, NULL );
    if( ! g_option_context_parse( opt_ctx, &argc, &argv, &err ) )
    {
        g_print( "%s", err->message );
        g_error_free( err );
        return 1;
    }

    if( lang )
        g_setenv( "LANGUAGE", lang, TRUE );
#if 0
    /* if the cache is already up-to-date, just leave it. */
    if( !force && is_menu_uptodate() )
    {
        g_print("upda-to-date, re-generation is not needed.");
        return 0;
    }
#endif

    /* some memory leaks happen here if g_free is not used to free the keys. */
    de_hash = g_hash_table_new_full(g_str_hash, g_str_equal, NULL, NULL);
    g_hash_table_insert( de_hash, (gpointer)"LXDE", (gpointer)SHOW_IN_LXDE );
    g_hash_table_insert( de_hash, (gpointer)"GNOME", (gpointer)SHOW_IN_GNOME );
    g_hash_table_insert( de_hash, (gpointer)"KDE", (gpointer)SHOW_IN_KDE );
    g_hash_table_insert( de_hash, (gpointer)"XFCE", (gpointer)SHOW_IN_XFCE );
    g_hash_table_insert( de_hash, (gpointer)"ROX", (gpointer)SHOW_IN_ROX );

    if(ifile)
        plus_ptr = strrchr(ifile, '+');

    if(plus_ptr != NULL && strcmp(plus_ptr, "+hidden") != 0)
        plus_ptr = NULL;

    if(plus_ptr)
    {
        *plus_ptr = '\0';
        menu_tree = gmenu_tree_lookup( ifile, GMENU_TREE_FLAGS_INCLUDE_NODISPLAY | GMENU_TREE_FLAGS_INCLUDE_EXCLUDED | GMENU_TREE_FLAGS_SHOW_EMPTY );
        *plus_ptr = '+';
    }
    else
        menu_tree = gmenu_tree_lookup( ifile, GMENU_TREE_FLAGS_INCLUDE_EXCLUDED );
    if( ! menu_tree )
    {
        g_print("Error loading source menu file: %s\n", ifile);
        return 1;
    }

    dir = g_path_get_dirname( ofile );
    if( !g_file_test( dir, G_FILE_TEST_EXISTS ) )
        g_mkdir_with_parents( dir, 0700 );
    g_free( dir );

    /* write the tree to cache. */
    tmp = g_malloc( strlen( ofile ) + 7 );
    strcpy( tmp, ofile );
    strcat( tmp, "XXXXXX" );
    ofd = g_mkstemp( tmp );
    if( ofd == -1 )
    {
        g_print( "Error writing output file: %s\n", g_strerror(errno) );
        return 1;
    }

    of = fdopen( ofd, "w" );
    if( ! of )
    {
        g_print( "Error writing output file: %s\n", ofile );
        return 1;
    }

    /* Version number should be added to the head of this cache file. */
    fprintf( of, "%d.%d\n", VER_MAJOR, VER_MINOR );

    /* the first line is menu name */
    fprintf( of, "%s\n", ifile );

    root_dir = gmenu_tree_get_root_directory( menu_tree );

    /* add the source menu file itself to the list of files requiring monitor */
    if(plus_ptr)
        *plus_ptr = '\0';
    if( g_path_is_absolute(ifile) )
    {
        if( ! g_slist_find_custom(all_used_files, ifile, (GCompareFunc)strcmp ) )
            all_used_files = g_slist_prepend(all_used_files, g_strdup(ifile));
    }
    else
    {
        char* file_name;
        xdg_cfg_dirs = g_get_system_config_dirs();
        menu_prefix = g_getenv("XDG_MENU_PREFIX");
        file_name = menu_prefix ? g_strconcat(menu_prefix, ifile, NULL) : ifile;
        for( pdir = xdg_cfg_dirs; *pdir; ++pdir )
        {
            menu_file = g_build_filename( *pdir, "menus", file_name, NULL );
            if( ! g_slist_find_custom(all_used_dirs, menu_file, (GCompareFunc)strcmp ) )
                all_used_files = g_slist_prepend(all_used_files, menu_file);
            else
                g_free( menu_file );
        }
        menu_file = g_build_filename( g_get_user_config_dir(), "menus", file_name, NULL );
        if( file_name != ifile )
            g_free(file_name);

        if( ! g_slist_find_custom(all_used_dirs, menu_file, (GCompareFunc)strcmp ) )
            all_used_files = g_slist_prepend(all_used_files, menu_file);
        else
            g_free(menu_file);
    }

    /* write a list of all files which need to be monitored for changes. */
    /* write number of files first */
    fprintf( of, "%d\n", g_slist_length(all_used_dirs) + g_slist_length(all_used_files) );

    /* list all files.
     * add D or F at the begin of each line to indicate whether it's a
     * file or directory. */
    for( l = all_used_dirs; l; l = l->next )
    {
        fprintf( of, "D%s\n", (char*)l->data );
    }
    for( l = all_used_files; l; l = l->next )
    {
        fprintf( of, "F%s\n", (char*)l->data );
    }

    /* write all DE names in this menu. Known DEs such as LXDE, GNOME, and KDE don't need to be listed here */
    if( g_hash_table_size(de_hash) > N_KNOWN_DESKTOPS ) /* if there are some unknown DEs added to the hash */
        g_hash_table_foreach(de_hash, (GHFunc)write_de_name, of );
    fputc('\n', of);

    /* write the whole menu tree */
    write_dir( of, root_dir );

    fclose( of );

    gmenu_tree_unref( menu_tree );

    g_hash_table_destroy(de_hash);

    if( g_rename( tmp, ofile ) == -1 )
    {
        g_print( "Error writing output file: %s\n", g_strerror( errno ) );
    }
    g_free( tmp );
    /* g_print("success!\n"); */
    return 0;
}
Exemplo n.º 16
0
/* (fall through - DEPRECATED)
 * enumerates system video devices
 * by checking /sys/class/video4linux
 * args: 
 * videodevice: current device string (default "/dev/video0")
 * 
 * returns: pointer to LDevices struct containing the video devices list */
LDevices *list_devices( gchar *videodevice )
{
	int ret=0;
	int fd=0;
	LDevices *listDevices = NULL;
	listDevices = g_new0( LDevices, 1);
	listDevices->listVidDevices = NULL;
	struct v4l2_capability v4l2_cap;
	GDir *v4l2_dir=NULL;
	GError *error=NULL;
	
	v4l2_dir = g_dir_open("/sys/class/video4linux",0,&error);
	if(v4l2_dir == NULL)
	{
		g_printerr ("opening '/sys/class/video4linux' failed: %s\n", 
			 error->message);
		g_error_free ( error );
		error=NULL;
		return NULL;
	}
	const gchar *v4l2_device;
	int num_dev = 0;
	
	while((v4l2_device = g_dir_read_name(v4l2_dir)) != NULL)
	{
		if(!(g_str_has_prefix(v4l2_device, "video")))
			continue;
		gchar *device = NULL;
		device = g_strjoin("/","/dev",v4l2_device,NULL);
		
		if ((fd = v4l2_open(device, O_RDWR | O_NONBLOCK, 0)) < 0) 
		{
			g_printerr("ERROR opening V4L interface for %s\n",
				device);
			g_free(device);
			continue; /*next dir entry*/
		} 
		else
		{
			ret = xioctl(fd, VIDIOC_QUERYCAP, &v4l2_cap);
			if (ret < 0) 
			{
				perror("VIDIOC_QUERYCAP error");
				g_printerr("   couldn't query device %s\n",
					device);
				g_free(device);
				v4l2_close(fd);
				continue; /*next dir entry*/
			}
			else
			{
				num_dev++;
				g_printf("%s - device %d\n", device, num_dev);
				listDevices->listVidDevices = g_renew(VidDevice, 
					listDevices->listVidDevices, 
					num_dev);
				listDevices->listVidDevices[num_dev-1].device = g_strdup(device);
				listDevices->listVidDevices[num_dev-1].name = g_strdup((gchar *) v4l2_cap.card);
				listDevices->listVidDevices[num_dev-1].driver = g_strdup((gchar *) v4l2_cap.driver);
				listDevices->listVidDevices[num_dev-1].location = g_strdup((gchar *) v4l2_cap.bus_info);
				listDevices->listVidDevices[num_dev-1].valid = 1;
				if(g_strcmp0(videodevice,listDevices->listVidDevices[num_dev-1].device)==0) 
				{
					listDevices->listVidDevices[num_dev-1].current = 1;
					listDevices->current_device = num_dev-1;
				}
				else
					listDevices->listVidDevices[num_dev-1].current = 0;
			}
		}
		g_free(device);
		v4l2_close(fd);
		
		listDevices->listVidDevices[num_dev-1].vendor = 0;
		listDevices->listVidDevices[num_dev-1].product = 0;
		
		gchar *vid_dev_lnk = g_strjoin("/","/sys/class/video4linux",v4l2_device,"device",NULL);
		gchar *device_lnk = g_file_read_link (vid_dev_lnk,&error);
		g_free(vid_dev_lnk);
		
		if(device_lnk == NULL)
		{
			g_printerr ("reading link '/sys/class/video4linux/%s/device' failed: %s\n",
				v4l2_device,
				error->message);
			g_error_free ( error );
			error=NULL;
			//if standard way fails try to get vid, pid from uvc device name 
			//we only need this info for Dynamic controls - uvc driver 
			listDevices->listVidDevices[num_dev-1].vendor = 0;  /*reset vid */
			listDevices->listVidDevices[num_dev-1].product = 0; /*reset pid */
			if(g_strcmp0(listDevices->listVidDevices[num_dev-1].driver,"uvcvideo") == 0)
			{
				sscanf(listDevices->listVidDevices[num_dev-1].name,"UVC Camera (%04x:%04x)",
					&(listDevices->listVidDevices[num_dev-1].vendor),
					&(listDevices->listVidDevices[num_dev-1].product));
			}
		}
		else
		{
			gchar *d_dir = g_strjoin("/","/sys/class/video4linux", v4l2_device, device_lnk, NULL);
			gchar *id_dir = g_path_get_dirname(d_dir);
			g_free(d_dir);
			
			gchar *idVendor = g_strjoin("/", id_dir, "idVendor" ,NULL);
			gchar *idProduct = g_strjoin("/", id_dir, "idProduct" ,NULL);
			
			//g_printf("idVendor: %s\n", idVendor);
			//g_printf("idProduct: %s\n", idProduct);
			FILE *vid_fp = g_fopen(idVendor,"r");
			if(vid_fp != NULL)
			{
				gchar code[5];
				if(fgets(code, sizeof(code), vid_fp) != NULL)
				{
					listDevices->listVidDevices[num_dev-1].vendor = g_ascii_strtoull(code, NULL, 16);
				}
				fclose (vid_fp);
			}
			else
			{
				g_printerr("couldn't open idVendor: %s\n", idVendor);
			}
			
			vid_fp = g_fopen(idProduct,"r");
			if(vid_fp != NULL)
			{
				gchar code[5];
				if(fgets(code, sizeof(code), vid_fp) != NULL)
				{
					listDevices->listVidDevices[num_dev-1].product = g_ascii_strtoull(code, NULL, 16);
				}
				fclose (vid_fp);
			}
			else
			{
				g_printerr("couldn't open idProduct: %s\n", idProduct);
			}
			
			g_free(id_dir);
			g_free(idVendor);
			g_free(idProduct);
		}
		
		g_free(device_lnk);
	}
	
	if(v4l2_dir != NULL) g_dir_close(v4l2_dir);
	
	listDevices->num_devices = num_dev;
	return(listDevices);
}
Exemplo n.º 17
0
void CMasterBiasDlg::Execute()
{
	char msg[256];
	char *folder, *filename;

	// Default state
	GtkTreeSelection *pSel = g_MainWnd->GetSelection();
	gtk_widget_set_sensitive(m_SelBtn, 
		gtk_tree_selection_count_selected_rows(pSel)>0);
	if (gtk_tree_selection_count_selected_rows(pSel)>1) 
		gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(m_SelBtn), true);
	else
		gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(m_AllBtn), true);

	// Restore last folder and file name
	folder = g_Project->GetStr("MasterBias", "Folder", NULL);
	if (!folder)
		folder = CConfig::GetStr("MasterBias", "Folder", NULL);
	if (!folder)
		folder = g_path_get_dirname(g_Project->Path());
	if (folder && g_file_test(folder, G_FILE_TEST_IS_DIR)) 
		gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(m_pDlg), folder);
	g_free(folder);
	filename = g_Project->GetStr("MasterBias", "File", "masterbias." FILE_EXTENSION_FITS);
	if (filename) 
		gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(m_pDlg), filename);
	g_free(filename);

	// Execute the dialog
	if (gtk_dialog_run(GTK_DIALOG(m_pDlg))!=GTK_RESPONSE_ACCEPT)
		return;
	gtk_widget_hide(m_pDlg);

	// Target file path and name
	m_FilePath = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(m_pDlg));
	CConfig::SetStr("BiasCorr", "File", m_FilePath);

	gchar *dirpath = g_path_get_dirname(m_FilePath);
	g_Project->SetStr("MasterBias", "Folder", dirpath);
	CConfig::SetStr("MasterBias", "Folder", dirpath);
	g_free(dirpath);
	gchar *basename = g_path_get_basename(m_FilePath);
	g_Project->SetStr("MasterBias", "File", basename);
	g_free(basename);

	// Make list of files
	m_FileList = NULL;
	if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(m_AllBtn))) {
		// All files
		GtkTreeModel *pList = g_Project->FileList();
		if (gtk_tree_model_iter_n_children(pList, NULL)>0) 
			gtk_tree_model_foreach(pList, foreach_all_files, &m_FileList);
		else
			ShowError(m_pParent, "There are no files in the project.");
	} else {
		// Selected files
		GtkTreeSelection *pSel = g_MainWnd->GetSelection();
		if (gtk_tree_selection_count_selected_rows(pSel)>0) 
			gtk_tree_selection_selected_foreach(pSel, foreach_sel_files, &m_FileList);
		else
			ShowError(m_pParent, "There are no selected files.");
	}

	// Process files
	if (m_FileList) {
		CProgressDlg pDlg(m_pParent, "Reading files");
		pDlg.SetMinMax(0, g_list_length(m_FileList));
		int res = pDlg.Execute(ExecuteProc, this);
		if (res!=0) {
			char *msg = cmpack_formaterror(res);
			ShowError(m_pParent, msg, true);
			cmpack_free(msg);
		} else if (!pDlg.Cancelled()) {
			sprintf(msg, "All %d file(s) were successfully processed.", m_InFiles);
			ShowInformation(m_pParent, msg, true);
			CCCDFileDlg *pdlg = new CCCDFileDlg();
			GError *error = NULL;
			if (pdlg->Load(m_FilePath, &error)) {
				pdlg->Show();
				CConfig::AddFileToRecentList(TYPE_IMAGE, m_FilePath);
			} else {
				if (error) {
					ShowError(m_pParent, error->message, true);
					g_error_free(error);
				}
				delete pdlg;
			}
		}
		g_list_foreach(m_FileList, (GFunc)gtk_tree_row_reference_free, NULL);
		g_list_free(m_FileList);
		m_FileList = NULL;
	}
	g_free(m_FilePath);
	m_FilePath = NULL;
	g_Project->Save();
	CConfig::Flush();
}
Exemplo n.º 18
0
static void
svgtopng (const gchar *src)
{
  gchar *dest;
  gchar *tmp;
  GdkPixbuf *pix;
  gchar *link;
  gchar *newlink;
  GError *error = NULL;
  gchar *dirname;
  gchar *basename;
  gint icon_size;

  if (!g_str_has_suffix (src, ".svg"))
    return;

  /* get parent directory name */
  dirname = g_path_get_dirname (src);
  basename = g_path_get_basename (dirname);
  g_free (dirname);
  if (basename == NULL)
    return;

  /* to go get an icon size */
  icon_size = atoi (basename);
  g_free (basename);
  if (icon_size == 0)
    {
      g_message ("Unable to extract icon size from directory name %s", src);
      return;
    }

  tmp = g_strndup (src, strlen (src) - 3);
  dest = g_strconcat (tmp, "png", NULL);
  g_free (tmp);

  if (!g_file_test (dest, G_FILE_TEST_EXISTS))
    {
      if (g_file_test (src, G_FILE_TEST_IS_SYMLINK))
        {
          link = g_file_read_link (src, NULL);
          if (link
              && g_str_has_suffix (link, ".svg"))
            {
              tmp = g_strndup (link, strlen (link) - 3);
              newlink = g_strconcat (tmp, "png", NULL);
              g_free (tmp);

              if (symlink (newlink, dest) == -1)
                g_message ("failed to create symlink: %s", g_strerror (errno));

              g_free (newlink);
            }
          g_free (link);
        }
      else
        {
          pix = gdk_pixbuf_new_from_file (src, &error);
          if (pix)
            {
              if (gdk_pixbuf_get_width (pix) > icon_size
                  || gdk_pixbuf_get_height (pix) > icon_size)
                {
                  g_message ("Skipping %s, size too big (%dx%d instead of %dx%d)",
                             dest, gdk_pixbuf_get_width (pix),
                             gdk_pixbuf_get_height (pix),
                             icon_size, icon_size);

                  g_object_unref (pix);
                  return;
                }

              if (!gdk_pixbuf_save (pix, dest, "png", &error, NULL))
                {
                  g_message ("Failed to save pixmap to %s: %s", dest, error->message);
                  g_error_free (error);
                }
              g_object_unref (pix);
            }
          else
            {
              g_message ("Failed to load svg %s: %s", src, error->message);
              g_error_free (error);
            }
        }
    }

  g_free (dest);
}
static int
handle_overwrite_open (const char    *filename,
		       gboolean       readable,
		       const char    *etag,
		       gboolean       create_backup,
		       char         **temp_filename,
		       GFileCreateFlags flags,
                       GFileInfo       *reference_info,
		       GCancellable  *cancellable,
		       GError       **error)
{
  int fd = -1;
  GLocalFileStat original_stat;
  char *current_etag;
  gboolean is_symlink;
  int open_flags;
  int res;
  int mode;

  mode = mode_from_flags_or_info (flags, reference_info);

  /* We only need read access to the original file if we are creating a backup.
   * We also add O_CREATE to avoid a race if the file was just removed */
  if (create_backup || readable)
    open_flags = O_RDWR | O_CREAT | O_BINARY;
  else
    open_flags = O_WRONLY | O_CREAT | O_BINARY;
  
  /* Some systems have O_NOFOLLOW, which lets us avoid some races
   * when finding out if the file we opened was a symlink */
#ifdef O_NOFOLLOW
  is_symlink = FALSE;
  fd = g_open (filename, open_flags | O_NOFOLLOW, mode);
  if (fd == -1 && errno == ELOOP)
    {
      /* Could be a symlink, or it could be a regular ELOOP error,
       * but then the next open will fail too. */
      is_symlink = TRUE;
      fd = g_open (filename, open_flags, mode);
    }
#else
  fd = g_open (filename, open_flags, mode);
  /* This is racy, but we do it as soon as possible to minimize the race */
  is_symlink = g_file_test (filename, G_FILE_TEST_IS_SYMLINK);
#endif
    
  if (fd == -1)
    {
      int errsv = errno;
      char *display_name = g_filename_display_name (filename);
      g_set_error (error, G_IO_ERROR,
		   g_io_error_from_errno (errsv),
		   _("Error opening file '%s': %s"),
		   display_name, g_strerror (errsv));
      g_free (display_name);
      return -1;
    }
  
#ifdef G_OS_WIN32
  res = _fstati64 (fd, &original_stat);
#else
  res = fstat (fd, &original_stat);
#endif

  if (res != 0) 
    {
      int errsv = errno;
      char *display_name = g_filename_display_name (filename);
      g_set_error (error, G_IO_ERROR,
		   g_io_error_from_errno (errsv),
		   _("Error when getting information for file '%s': %s"),
		   display_name, g_strerror (errsv));
      g_free (display_name);
      goto err_out;
    }
  
  /* not a regular file */
  if (!S_ISREG (original_stat.st_mode))
    {
      if (S_ISDIR (original_stat.st_mode))
	g_set_error_literal (error,
                             G_IO_ERROR,
                             G_IO_ERROR_IS_DIRECTORY,
                             _("Target file is a directory"));
      else
	g_set_error_literal (error,
                             G_IO_ERROR,
                             G_IO_ERROR_NOT_REGULAR_FILE,
                             _("Target file is not a regular file"));
      goto err_out;
    }
  
  if (etag != NULL)
    {
      current_etag = _g_local_file_info_create_etag (&original_stat);
      if (strcmp (etag, current_etag) != 0)
	{
	  g_set_error_literal (error,
                               G_IO_ERROR,
                               G_IO_ERROR_WRONG_ETAG,
                               _("The file was externally modified"));
	  g_free (current_etag);
	  goto err_out;
	}
      g_free (current_etag);
    }

  /* We use two backup strategies.
   * The first one (which is faster) consist in saving to a
   * tmp file then rename the original file to the backup and the
   * tmp file to the original name. This is fast but doesn't work
   * when the file is a link (hard or symbolic) or when we can't
   * write to the current dir or can't set the permissions on the
   * new file. 
   * The second strategy consist simply in copying the old file
   * to a backup file and rewrite the contents of the file.
   */
  
  if ((flags & G_FILE_CREATE_REPLACE_DESTINATION) ||
      (!(original_stat.st_nlink > 1) && !is_symlink))
    {
      char *dirname, *tmp_filename;
      int tmpfd;
      
      dirname = g_path_get_dirname (filename);
      tmp_filename = g_build_filename (dirname, ".goutputstream-XXXXXX", NULL);
      g_free (dirname);

      tmpfd = g_mkstemp_full (tmp_filename, (readable ? O_RDWR : O_WRONLY) | O_BINARY, mode);
      if (tmpfd == -1)
	{
	  g_free (tmp_filename);
	  goto fallback_strategy;
	}
      
      /* try to keep permissions (unless replacing) */

      if ( ! (flags & G_FILE_CREATE_REPLACE_DESTINATION) &&
	   (
#ifdef HAVE_FCHOWN
	    fchown (tmpfd, original_stat.st_uid, original_stat.st_gid) == -1 ||
#endif
#ifdef HAVE_FCHMOD
	    fchmod (tmpfd, original_stat.st_mode) == -1 ||
#endif
	    0
	    )
	  )
	{
          GLocalFileStat tmp_statbuf;
          int tres;

#ifdef G_OS_WIN32
          tres = _fstati64 (tmpfd, &tmp_statbuf);
#else
          tres = fstat (tmpfd, &tmp_statbuf);
#endif
	  /* Check that we really needed to change something */
	  if (tres != 0 ||
	      original_stat.st_uid != tmp_statbuf.st_uid ||
	      original_stat.st_gid != tmp_statbuf.st_gid ||
	      original_stat.st_mode != tmp_statbuf.st_mode)
	    {
	      (void) g_close (tmpfd, NULL);
	      g_unlink (tmp_filename);
	      g_free (tmp_filename);
	      goto fallback_strategy;
	    }
	}

      (void) g_close (fd, NULL);
      *temp_filename = tmp_filename;
      return tmpfd;
    }

 fallback_strategy:

  if (create_backup)
    {
#if defined(HAVE_FCHOWN) && defined(HAVE_FCHMOD)
      struct stat tmp_statbuf;      
#endif
      char *backup_filename;
      int bfd;
      
      backup_filename = create_backup_filename (filename);

      if (g_unlink (backup_filename) == -1 && errno != ENOENT)
	{
	  g_set_error_literal (error,
                               G_IO_ERROR,
                               G_IO_ERROR_CANT_CREATE_BACKUP,
                               _("Backup file creation failed"));
	  g_free (backup_filename);
	  goto err_out;
	}

      bfd = g_open (backup_filename,
		    O_WRONLY | O_CREAT | O_EXCL | O_BINARY,
		    original_stat.st_mode & 0777);

      if (bfd == -1)
	{
	  g_set_error_literal (error,
                               G_IO_ERROR,
                               G_IO_ERROR_CANT_CREATE_BACKUP,
                               _("Backup file creation failed"));
	  g_free (backup_filename);
	  goto err_out;
	}

      /* If needed, Try to set the group of the backup same as the
       * original file. If this fails, set the protection
       * bits for the group same as the protection bits for
       * others. */
#if defined(HAVE_FCHOWN) && defined(HAVE_FCHMOD)
      if (fstat (bfd, &tmp_statbuf) != 0)
	{
	  g_set_error_literal (error,
                               G_IO_ERROR,
                               G_IO_ERROR_CANT_CREATE_BACKUP,
                               _("Backup file creation failed"));
	  g_unlink (backup_filename);
	  g_free (backup_filename);
	  goto err_out;
	}
      
      if ((original_stat.st_gid != tmp_statbuf.st_gid)  &&
	  fchown (bfd, (uid_t) -1, original_stat.st_gid) != 0)
	{
	  if (fchmod (bfd,
		      (original_stat.st_mode & 0707) |
		      ((original_stat.st_mode & 07) << 3)) != 0)
	    {
	      g_set_error_literal (error,
                                   G_IO_ERROR,
                                   G_IO_ERROR_CANT_CREATE_BACKUP,
                                   _("Backup file creation failed"));
	      g_unlink (backup_filename);
	      (void) g_close (bfd, NULL);
	      g_free (backup_filename);
	      goto err_out;
	    }
	}
#endif

      if (!copy_file_data (fd, bfd, NULL))
	{
	  g_set_error_literal (error,
                               G_IO_ERROR,
                               G_IO_ERROR_CANT_CREATE_BACKUP,
                               _("Backup file creation failed"));
	  g_unlink (backup_filename);
          (void) g_close (bfd, NULL);
	  g_free (backup_filename);
	  
	  goto err_out;
	}
      
      (void) g_close (bfd, NULL);
      g_free (backup_filename);

      /* Seek back to the start of the file after the backup copy */
      if (lseek (fd, 0, SEEK_SET) == -1)
	{
          int errsv = errno;

	  g_set_error (error, G_IO_ERROR,
		       g_io_error_from_errno (errsv),
		       _("Error seeking in file: %s"),
		       g_strerror (errsv));
	  goto err_out;
	}
    }

  if (flags & G_FILE_CREATE_REPLACE_DESTINATION)
    {
      (void) g_close (fd, NULL);
      
      if (g_unlink (filename) != 0)
	{
	  int errsv = errno;
	  
	  g_set_error (error, G_IO_ERROR,
		       g_io_error_from_errno (errsv),
		       _("Error removing old file: %s"),
		       g_strerror (errsv));
	  goto err_out2;
	}

      if (readable)
	open_flags = O_RDWR | O_CREAT | O_BINARY;
      else
	open_flags = O_WRONLY | O_CREAT | O_BINARY;
      fd = g_open (filename, open_flags, mode);
      if (fd == -1)
	{
	  int errsv = errno;
	  char *display_name = g_filename_display_name (filename);
	  g_set_error (error, G_IO_ERROR,
		       g_io_error_from_errno (errsv),
		       _("Error opening file '%s': %s"),
		       display_name, g_strerror (errsv));
	  g_free (display_name);
	  goto err_out2;
	}
    }
  else
    {
      /* Truncate the file at the start */
#ifdef G_OS_WIN32
      if (g_win32_ftruncate (fd, 0) == -1)
#else
	if (ftruncate (fd, 0) == -1)
#endif
	  {
	    int errsv = errno;
	    
	    g_set_error (error, G_IO_ERROR,
			 g_io_error_from_errno (errsv),
			 _("Error truncating file: %s"),
			 g_strerror (errsv));
	    goto err_out;
	  }
    }
    
  return fd;

 err_out:
  (void) g_close (fd, NULL);
 err_out2:
  return -1;
}
Exemplo n.º 20
0
gint
main (gint argc, gchar ** argv)
{
  gchar *filename;
  GModule *core_module;
  OMX_ERRORTYPE err;
  OMX_ERRORTYPE (*omx_init) (void);
  OMX_ERRORTYPE (*omx_component_name_enum) (OMX_STRING cComponentName,
      OMX_U32 nNameLength, OMX_U32 nIndex);
  OMX_ERRORTYPE (*omx_get_roles_of_component) (OMX_STRING compName,
      OMX_U32 * pNumRoles, OMX_U8 ** roles);
  guint32 i;

  if (argc != 2) {
    g_printerr ("Usage: %s /path/to/libopenmaxil.so\n", argv[0]);
    return -1;
  }

  filename = argv[1];

  if (!g_path_is_absolute (filename)) {
    g_printerr ("'%s' is not an absolute filename\n", filename);
    return -1;
  }

  /* Hack for the Broadcom OpenMAX IL implementation */
  if (g_str_has_suffix (filename, "vc/lib/libopenmaxil.so")) {
    gchar *bcm_host_filename;
    gchar *bcm_host_path;
    GModule *bcm_host_module;
    void (*bcm_host_init) (void);

    bcm_host_path = g_path_get_dirname (filename);
    bcm_host_filename =
        g_build_filename (bcm_host_path, "libbcm_host.so", NULL);

    bcm_host_module = g_module_open (bcm_host_filename, G_MODULE_BIND_LAZY);

    g_free (bcm_host_filename);
    g_free (bcm_host_path);

    if (!bcm_host_module) {
      g_printerr ("Failed to load 'libbcm_host.so'\n");
      return -1;
    }

    if (!g_module_symbol (bcm_host_module, "bcm_host_init",
            (gpointer *) & bcm_host_init)) {
      g_printerr ("Failed to find 'bcm_host_init' in 'libbcm_host.so'\n");
      return -1;
    }

    bcm_host_init ();
  }

  core_module = g_module_open (filename, G_MODULE_BIND_LAZY);
  if (!core_module) {
    g_printerr ("Failed to load '%s'\n", filename);
    return -1;
  }

  if (!g_module_symbol (core_module, "OMX_Init", (gpointer *) & omx_init)) {
    g_printerr ("Failed to find '%s' in '%s'\n", "OMX_Init", filename);
    return -1;
  }

  if (!g_module_symbol (core_module, "OMX_ComponentNameEnum",
          (gpointer *) & omx_component_name_enum)) {
    g_printerr ("Failed to find '%s' in '%s'\n", "OMX_ComponentNameEnum",
        filename);
    return -1;
  }

  if (!g_module_symbol (core_module, "OMX_GetRolesOfComponent",
          (gpointer *) & omx_get_roles_of_component)) {
    g_printerr ("Failed to find '%s' in '%s'\n", "OMX_GetRolesOfComponent",
        filename);
    return -1;
  }


  if ((err = omx_init ()) != OMX_ErrorNone) {
    g_printerr ("Failed to initialize core: %d\n", err);
    return -1;
  }

  i = 0;
  while (err == OMX_ErrorNone) {
    gchar component_name[1024];

    err = omx_component_name_enum (component_name, sizeof (component_name), i);
    if (err == OMX_ErrorNone || err == OMX_ErrorNoMore) {
      guint32 nroles;

      g_print ("Component %d: %s\n", i, component_name);

      if (omx_get_roles_of_component (component_name, (OMX_U32 *) & nroles,
              NULL) == OMX_ErrorNone && nroles > 0) {
        gchar **roles = g_new (gchar *, nroles);
        gint j;

        roles[0] = g_new0 (gchar, 129 * nroles);
        for (j = 1; j < nroles; j++) {
          roles[j] = roles[j - 1] + 129;
        }

        if (omx_get_roles_of_component (component_name, (OMX_U32 *) & nroles,
                (OMX_U8 **) roles) == OMX_ErrorNone) {
          for (j = 0; j < nroles; j++) {
            g_print ("  Role %d: %s\n", j, roles[j]);
          }
        }
        g_free (roles[0]);
        g_free (roles);
      }
    }
Exemplo n.º 21
0
int
main(int argc,
     char *argv[])
{
   gPrefs = Pref_Init(VGAUTH_PREF_CONFIG_FILENAME);

   /*
    * Determine where the service is running from, so resources can
    * be found relative to it.
    */
   if (!g_path_is_absolute(argv[0])) {
      gchar *abs = g_find_program_in_path(argv[0]);
      if (abs == NULL || g_strcmp0(abs, argv[0]) == 0) {
         gchar *cwd = g_get_current_dir();
         g_free(abs);
         abs = g_build_filename(cwd, argv[0], NULL);
         g_free(cwd);
      }
      gInstallDir = g_path_get_dirname(abs);
      g_free(abs);
   } else {
      gInstallDir = g_path_get_dirname(argv[0]);
   }

#ifdef _WIN32
#if SUPPORT_WIN_SERVICE

   /*
    * This is the path for the service control manager.
    */
   if (argc == 1) {
      ServiceRunAsService();
      return 0;
   } else if (argc == 2) {
      // register
      if (g_strcmp0(argv[1], "-r") == 0) {
         ServiceDoRegisterService(argv[0], TRUE);
         return 0;
      // unregister
      } else if (g_strcmp0(argv[1], "-u") == 0) {
         ServiceDoRegisterService(argv[0], FALSE);
         return 0;
      // run as a cmdline app for debugging
      } else if (g_strcmp0(argv[1], "-d") == 0) {
         Service_SetLogOnStdout(TRUE);
         Service_InitLogging(FALSE, FALSE);
         ServiceStartAndRun();
         return 0;
       // run on cmdline, using log file
      } else if (g_strcmp0(argv[1], "-s") == 0) {
         Service_InitLogging(FALSE, FALSE);
         ServiceStartAndRun();
         return 0;
      } else if (g_strcmp0(argv[1], "-h") == 0) {
         ServiceHelp(argv[0]);
         return 0;
      }
   }

#else
   Service_SetLogOnStdout(TRUE);
   Service_InitLogging(FALSE, FALSE);
   ServiceStartAndRun();
#endif
#else // !_WIN32

#if USE_POSIX_SERVICE
   /*
    * Parse arguments.
    *
    * "-b" tells it to run as a daemon.
    * "-s" tells it to run in service mode (logging to a file).
    * "-k" tells it to kill itself.
    *
    * When running as a daemon, we restart, except with -b changed
    * to -s so we properly log to a file.
    *
    * This code assumes the only arguments supported are "-b" and "-k".
    * The replacement of "-b" before calling ServiceDamonize()
    * will need work if that changes.
    */

   if (argc > 1) {
      if (g_strcmp0(argv[1], "-k") == 0) {            // kill mode
         if (!ServiceSuicide(pidFileName)) {
            exit(-1);
         } else {
            exit(0);
         }
      } else if (g_strcmp0(argv[1], "-s") == 0) {     // service mode
         isRunningAsService = TRUE;
         Service_InitLogging(FALSE, FALSE);
      } else if (g_strcmp0(argv[1], "-b") == 0) {     // background mode
         Service_InitLogging(FALSE, FALSE);
         /*
          * We have to remove this flag to prevent an infinite loop.
          */
         argv[1] = g_strdup("-s");
         if (!ServiceDaemonize(argv[0],
                               argv,
                               SERVICE_DAEMONIZE_LOCKPID,
                               pidFileName)) {
            Warning("%s: failed to daemonize\n", __FUNCTION__);
            return -1;
         }
         // NOTREACHED
         return 0;
      } else if (g_strcmp0(argv[1], "-h") == 0) {     // help
         ServiceHelp(argv[0]);
         return 0;
      } else {
         Warning("%s: unrecognized args\n", __FUNCTION__);
      }
   } else {
      /* The foreground mode */
      Service_SetLogOnStdout(TRUE);
      Service_InitLogging(FALSE, FALSE);
   }
#endif   // USE_POSIX_SERVICE
   ServiceSetSignalHandlers();
   ServiceStartAndRun();

#endif   // !_WIN32

   return 0;
}
Exemplo n.º 22
0
AnjutaPluginHandle*
anjuta_plugin_handle_new (const gchar *plugin_desc_path)
{
	AnjutaPluginHandle *plugin_handle;
	AnjutaPluginDescription *desc;
	char *str;
	gboolean enable;
	gchar *contents = NULL;
	gboolean success = TRUE;
	
	/* Load file content */
	if (g_file_get_contents (plugin_desc_path, &contents, NULL, NULL)) {
		
		desc = anjuta_plugin_description_new_from_string (contents, NULL);
		g_free (contents);
		if (!desc) {
			g_warning ("Bad plugin file: %s\n", plugin_desc_path);
			return NULL;
		}
	}
	else
	{
		return NULL;
	}
	
	plugin_handle = g_object_new (ANJUTA_TYPE_PLUGIN_HANDLE, NULL);
	
	/* Initialize plugin handle */
	plugin_handle->priv->description = desc;
	plugin_handle->priv->user_activatable = TRUE;
	plugin_handle->priv->resident = TRUE;
	plugin_handle->priv->path = g_path_get_dirname (plugin_desc_path);
	
	if (anjuta_plugin_description_get_string (desc, "Anjuta Plugin",
											  "Location", &str)) {
		plugin_handle->priv->id = str;
	} else {
		g_warning ("Couldn't find 'Location'");
		success = FALSE;
	}
	
	if (anjuta_plugin_description_get_locale_string (desc, "Anjuta Plugin",
													 "Name", &str)) {
		plugin_handle->priv->name = str;
	} else {
		g_warning ("couldn't find 'Name' attribute.");
		success = FALSE;
	}

	if (anjuta_plugin_description_get_locale_string (desc, "Anjuta Plugin",
													 "Description", &str)) {
		plugin_handle->priv->about = str;
	} else {
		g_warning ("Couldn't find 'Description' attribute.");
		success = FALSE;
	}

	if (anjuta_plugin_description_get_string (desc, "Anjuta Plugin",
									   "Icon", &str)) {
		plugin_handle->priv->icon_path = get_icon_path (str);
		g_free (str);
	}

	if (anjuta_plugin_description_get_string (desc, "Anjuta Plugin",
											  "Dependencies",
											  &str)) {
		plugin_handle->priv->dependency_names = property_to_list (str);
		g_free (str);
	}

	if (anjuta_plugin_description_get_string (desc, "Anjuta Plugin",
											  "Interfaces",
											  &str)) {
		plugin_handle->priv->interfaces = property_to_list (str);
		g_free (str);
	}
	
	if (anjuta_plugin_description_get_boolean (desc, "Anjuta Plugin",
											  "UserActivatable", &enable)) {
		plugin_handle->priv->user_activatable = enable;
		/*
		DEBUG_PRINT ("Plugin '%s' is not user activatable",
					 plugin_handle->priv->name?
					 plugin_handle->priv->name : "Unknown");
		*/
	}
	
	if (anjuta_plugin_description_get_string (desc, "Anjuta Plugin",
											  "Resident", &str)) {
		if (str && strcasecmp (str, "no") == 0)
		{
			plugin_handle->priv->resident = FALSE;
		}
		g_free (str);
	}

	if (anjuta_plugin_description_get_string (desc, "Anjuta Plugin",
											  "Language", &str)) {
		plugin_handle->priv->language = str;
	}
	
	if (!success) {
		g_object_unref (plugin_handle);
		plugin_handle = NULL;
	}

	return plugin_handle;
}
Exemplo n.º 23
0
static void dt_film_import1(dt_job_t *job, dt_film_t *film)
{
  gboolean recursive = dt_conf_get_bool("ui_last/import_recursive");

  /* first of all gather all images to import */
  GList *images = NULL;
  images = _film_recursive_get_files(film->dirname, recursive, &images);
  if(g_list_length(images) == 0)
  {
    dt_control_log(_("no supported images were found to be imported"));
    return;
  }

#ifdef USE_LUA
  /* pre-sort image list for easier handling in Lua code */
  images = g_list_sort(images, (GCompareFunc)_film_filename_cmp);

  dt_lua_lock();
  lua_State *L = darktable.lua_state.state;
  {
    GList *elt = images;
    lua_newtable(L);
    while(elt)
    {
      lua_pushstring(L, elt->data);
      luaL_ref(L, -2);
      elt = g_list_next(elt);
    }
  }
  lua_pushvalue(L, -1);
  dt_lua_event_trigger(L, "pre-import", 1);
  {
    g_list_free_full(images, g_free);
    // recreate list of images
    images = NULL;
    lua_pushnil(L); /* first key */
    while(lua_next(L, -2) != 0)
    {
      /* uses 'key' (at index -2) and 'value' (at index -1) */
      void *filename = strdup(luaL_checkstring(L, -1));
      lua_pop(L, 1);
      images = g_list_prepend(images, filename);
    }
  }

  lua_pop(L, 1); // remove the table again from the stack

  dt_lua_unlock();
#endif

  if(g_list_length(images) == 0)
  {
    // no error message, lua probably emptied the list on purpose
    return;
  }

  /* we got ourself a list of images, lets sort and start import */
  images = g_list_sort(images, (GCompareFunc)_film_filename_cmp);

  /* let's start import of images */
  gchar message[512] = { 0 };
  double fraction = 0;
  guint total = g_list_length(images);
  g_snprintf(message, sizeof(message) - 1, ngettext("importing %d image", "importing %d images", total), total);
  dt_control_job_set_progress_message(job, message);


  /* loop thru the images and import to current film roll */
  dt_film_t *cfr = film;
  GList *image = g_list_first(images);
  do
  {
    gchar *cdn = g_path_get_dirname((const gchar *)image->data);

    /* check if we need to initialize a new filmroll */
    if(!cfr || g_strcmp0(cfr->dirname, cdn) != 0)
    {
      // FIXME: maybe refactor into function and call it?
      if(cfr && cfr->dir)
      {
        /* check if we can find a gpx data file to be auto applied
           to images in the jsut imported filmroll */
        g_dir_rewind(cfr->dir);
        const gchar *dfn = NULL;
        while((dfn = g_dir_read_name(cfr->dir)) != NULL)
        {
          /* check if we have a gpx to be auto applied to filmroll */
          size_t len = strlen(dfn);
          if(strcmp(dfn + len - 4, ".gpx") == 0 || strcmp(dfn + len - 4, ".GPX") == 0)
          {
            gchar *gpx_file = g_build_path(G_DIR_SEPARATOR_S, cfr->dirname, dfn, NULL);
            gchar *tz = dt_conf_get_string("plugins/lighttable/geotagging/tz");
            dt_control_gpx_apply(gpx_file, cfr->id, tz);
            g_free(gpx_file);
            g_free(tz);
          }
        }
      }

      /* cleanup previously imported filmroll*/
      if(cfr && cfr != film)
      {
        if(dt_film_is_empty(cfr->id))
        {
          dt_film_remove(cfr->id);
        }
        dt_film_cleanup(cfr);
        free(cfr);
        cfr = NULL;
      }

      /* initialize and create a new film to import to */
      cfr = malloc(sizeof(dt_film_t));
      dt_film_init(cfr);
      dt_film_new(cfr, cdn);
    }

    g_free(cdn);

    /* import image */
    dt_image_import(cfr->id, (const gchar *)image->data, FALSE);

    fraction += 1.0 / total;
    dt_control_job_set_progress(job, fraction);


  } while((image = g_list_next(image)) != NULL);

  g_list_free_full(images, g_free);

  // only redraw at the end, to not spam the cpu with exposure events
  dt_control_queue_redraw_center();
  dt_control_signal_raise(darktable.signals, DT_SIGNAL_TAG_CHANGED);

  dt_control_signal_raise(darktable.signals, DT_SIGNAL_FILMROLLS_IMPORTED, film->id);

  // FIXME: maybe refactor into function and call it?
  if(cfr && cfr->dir)
  {
    /* check if we can find a gpx data file to be auto applied
       to images in the just imported filmroll */
    g_dir_rewind(cfr->dir);
    const gchar *dfn = NULL;
    while((dfn = g_dir_read_name(cfr->dir)) != NULL)
    {
      /* check if we have a gpx to be auto applied to filmroll */
      size_t len = strlen(dfn);
      if(strcmp(dfn + len - 4, ".gpx") == 0 || strcmp(dfn + len - 4, ".GPX") == 0)
      {
        gchar *gpx_file = g_build_path(G_DIR_SEPARATOR_S, cfr->dirname, dfn, NULL);
        gchar *tz = dt_conf_get_string("plugins/lighttable/geotagging/tz");
        dt_control_gpx_apply(gpx_file, cfr->id, tz);
        g_free(gpx_file);
        g_free(tz);
      }
    }
  }

  /* cleanup previously imported filmroll*/
  if(cfr && cfr != film)
  {
    dt_film_cleanup(cfr);
    free(cfr);
  }
}
Exemplo n.º 24
0
guint encoder_initialize (GArray *earray, gchar *job, EncoderOutput *encoders, Source *source)
{
    gint i, j, k;
    gchar *job_name, *pipeline;
    Encoder *encoder;
    EncoderStream *estream;
    SourceStream *sstream;
    gchar **bins;
    gsize count;

    job_name = jobdesc_get_name (job);
    count = jobdesc_encoders_count (job);
    for (i = 0; i < count; i++) {
        pipeline = g_strdup_printf ("encoder.%d", i);
        encoder = encoder_new ("name", pipeline, NULL);
        encoder->job_name = g_strdup (job_name);
        encoder->id = i;
        encoder->last_running_time = GST_CLOCK_TIME_NONE;
        encoder->output = &(encoders[i]);
        encoder->segment_duration = jobdesc_m3u8streaming_segment_duration (job);
        encoder->duration_accumulation = 0;
        encoder->last_segment_duration = 0;
        encoder->force_key_count = 0;
        encoder->has_video = FALSE;
        encoder->has_audio_only = FALSE;
        encoder->has_tssegment = FALSE;

        bins = jobdesc_bins (job, pipeline);
        if (encoder_extract_streams (encoder, bins) != 0) {
            GST_ERROR ("extract encoder %s streams failure", encoder->name);
            g_free (job_name);
            g_free (pipeline);
            g_strfreev (bins);
            return 1;
        }
        g_strfreev (bins);

        for (j = 0; j < encoder->streams->len; j++) {
            estream = g_array_index (encoder->streams, gpointer, j);
            estream->state = &(encoders[i].streams[j]);
            g_strlcpy (encoders[i].streams[j].name, estream->name, STREAM_NAME_LEN);
            estream->encoder = encoder;
            estream->source = NULL;
            for (k = 0; k < source->streams->len; k++) {
                sstream = g_array_index (source->streams, gpointer, k);
                if (g_strcmp0 (sstream->name, estream->name) == 0) {
                    estream->source = sstream;
                    estream->current_position = -1;
                    estream->system_clock = encoder->system_clock;
                    g_array_append_val (sstream->encoders, estream);
                    break;
                }
            }
            if (estream->source == NULL) {
                GST_ERROR ("cant find job %s source %s.", job_name, estream->name);
                g_free (job_name);
                g_free (pipeline);
                return 1;
            }
        }

        /* mkdir for transcode job. */
        if (!jobdesc_is_live (job)) {
            gchar *locations[] = {"%s.elements.filesink.property.location", "%s.elements.hlssink.property.location", NULL};
            gchar *p, *value, **location;

            location = locations;
            while (*location != NULL) {
                p = g_strdup_printf (*location, pipeline);
                value = jobdesc_element_property_value (job, p);
                g_free (p);
                if (value != NULL) {
                    break;
                }
                location += 1;
            }
            if (*location == NULL) {
                GST_ERROR ("No location found for transcode");
                return 1;
            }
            p = g_path_get_dirname (value);
            g_free (value);
            if (g_mkdir_with_parents (p, 0755) != 0) {
                GST_ERROR ("Can't open or create directory: %s.", p);
                g_free (p);
                return 1;
            }
            g_free (p);
        }

        /* parse bins and create pipeline. */
        encoder->bins = bins_parse (job, pipeline);
        if (encoder->bins == NULL) {
            GST_ERROR ("parse job %s bins error", job_name);
            g_free (job_name);
            g_free (pipeline);
            return 1;
        }
        complete_request_element (encoder->bins);
        if (create_encoder_pipeline (encoder) != 0) {
            GST_ERROR ("create encoder %s pipeline failure", encoder->name);
            g_free (job_name);
            g_free (pipeline);
            return 1;
        }

        /* parse udpstreaming */
        udpstreaming_parse (job, encoder);

        /* m3u8 playlist */
        encoder->is_first_key = TRUE;
        if (jobdesc_m3u8streaming (job)) {
            memset (&(encoder->msg_sock_addr), 0, sizeof (struct sockaddr_un));
            encoder->msg_sock_addr.sun_family = AF_UNIX;
            strncpy (encoder->msg_sock_addr.sun_path, MSG_SOCK_PATH, sizeof (encoder->msg_sock_addr.sun_path) - 1);
            encoder->msg_sock = socket(AF_UNIX, SOCK_DGRAM | SOCK_NONBLOCK, 0);
            encoder->has_m3u8_output = TRUE;

        } else {
            encoder->has_m3u8_output = FALSE;
        }

        g_free (pipeline);
        g_array_append_val (earray, encoder);
    }
    g_free (job_name);

    return 0;
}
Exemplo n.º 25
0
/* Callback for sending file as attachment */
static void
send_as_attachment(G_GNUC_UNUSED GtkMenuItem *menuitem, G_GNUC_UNUSED gpointer gdata)
{
	GeanyDocument *doc;
	gchar	*locale_filename = NULL;
	gchar	*command = NULL;
	GError	*error = NULL;
	GString	*cmd_str = NULL;
	gchar 		*data;

	doc = document_get_current();

	if (doc->file_name == NULL)
	{
		dialogs_show_save_as();
	}
	else
	{
		document_save_file(doc, FALSE);
	}

    if (doc->file_name != NULL)
	{
		if (mailer)
		{
			locale_filename = utils_get_locale_from_utf8(doc->file_name);
			cmd_str = g_string_new(mailer);
			if ((use_address_dialog == TRUE) && (g_strrstr(mailer, "%r") != NULL))
			{
				GKeyFile *config = NULL;
				gchar *config_dir = NULL;
 				gchar *input = dialogs_show_input(_("Recipient's Address"),
										GTK_WINDOW(geany->main_widgets->window),
										_("Enter the recipient's e-mail address:"),
										address);

				if (input)
				{
					config = g_key_file_new();
					g_key_file_load_from_file(config, config_file, G_KEY_FILE_NONE, NULL);

					g_free(address);
 					address = input;

 					g_key_file_set_string(config, "tools", "address", address);
 				}
 				else
 				{
					g_string_free(cmd_str, TRUE);
					g_free(locale_filename);
					return;
				}

				config_dir = g_path_get_dirname(config_file);
				if (! g_file_test(config_dir, G_FILE_TEST_IS_DIR) &&
				      utils_mkdir(config_dir, TRUE) != 0)
 				{
 					dialogs_show_msgbox(GTK_MESSAGE_ERROR,
 						_("Plugin configuration directory could not be created."));
 				}
 				else
 				{
 					/* write config to file */
 					data = g_key_file_to_data(config, NULL, NULL);
 					utils_write_file(config_file, data);
					g_free(data);
 				}
				g_key_file_free(config);
				g_free(config_dir);
 			}

			if (! utils_string_replace_all(cmd_str, "%f", locale_filename))
				ui_set_statusbar(FALSE,
				_("Filename placeholder not found. The executed command might have failed."));

			if (use_address_dialog == TRUE && address != NULL)
			{
				if (! utils_string_replace_all(cmd_str, "%r", address))
 					ui_set_statusbar(FALSE,
					_("Recipient address placeholder not found. The executed command might have failed."));
			}
			else
			{
				/* Removes %r if option was not activ but was included into command */
				utils_string_replace_all(cmd_str, "%r", "");
			}

			utils_string_replace_all(cmd_str, "%b", g_path_get_basename(locale_filename));

			command = g_string_free(cmd_str, FALSE);
			g_spawn_command_line_async(command, &error);
			if (error != NULL)
			{
				ui_set_statusbar(FALSE, _("Could not execute mailer. Please check your configuration."));
				g_error_free(error);
			}

			g_free(locale_filename);
			g_free(command);
		}
		else
		{
			ui_set_statusbar(FALSE, _("Please define a mail client first."));
		}
	}
	else
	{
		ui_set_statusbar(FALSE, _("File has to be saved before sending."));
	}
}
Exemplo n.º 26
0
static void _lib_import_single_image_callback(GtkWidget *widget,gpointer user_data) 
{
  GtkWidget *win = dt_ui_main_window(darktable.gui->ui);
  GtkWidget *filechooser = gtk_file_chooser_dialog_new (_("import image"),
                           GTK_WINDOW (win),
                           GTK_FILE_CHOOSER_ACTION_OPEN,
                           GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                           GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
                           (char *)NULL);

  gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(filechooser), TRUE);

  char *last_directory = dt_conf_get_string("ui_last/import_last_directory");
  if(last_directory != NULL)
    gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER (filechooser), last_directory);

  char *cp, **extensions, ext[1024];
  GtkFileFilter *filter;
  filter = GTK_FILE_FILTER(gtk_file_filter_new());
  extensions = g_strsplit(dt_supported_extensions, ",", 100);
  for(char **i=extensions; *i!=NULL; i++)
  {
    snprintf(ext, 1024, "*.%s", *i);
    gtk_file_filter_add_pattern(filter, ext);
    gtk_file_filter_add_pattern(filter, cp=g_ascii_strup(ext, -1));
    g_free(cp);
  }
  g_strfreev(extensions);
  gtk_file_filter_set_name(filter, _("supported images"));
  gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(filechooser), filter);

  filter = GTK_FILE_FILTER(gtk_file_filter_new());
  gtk_file_filter_add_pattern(filter, "*");
  gtk_file_filter_set_name(filter, _("all files"));
  gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(filechooser), filter);

  if (gtk_dialog_run (GTK_DIALOG (filechooser)) == GTK_RESPONSE_ACCEPT)
  {
    dt_conf_set_string("ui_last/import_last_directory", gtk_file_chooser_get_current_folder(GTK_FILE_CHOOSER (filechooser)));

    char *filename = NULL;
    dt_film_t film;
    GSList *list = gtk_file_chooser_get_filenames (GTK_FILE_CHOOSER (filechooser));
    GSList *it = list;
    int id = 0;
    int filmid = 0;
    while(it)
    {
      filename = (char *)it->data;
      gchar *directory = g_path_get_dirname((const gchar *)filename);
      filmid = dt_film_new(&film, directory);
      id = dt_image_import(filmid, filename, TRUE);
      if(!id) dt_control_log(_("error loading file `%s'"), filename);
      g_free (filename);
      g_free (directory);
      it = g_slist_next(it);
    }

    if(id)
    {
      dt_film_open(filmid);
      // make sure buffers are loaded (load full for testing)
      dt_mipmap_buffer_t buf;
      dt_mipmap_cache_read_get(darktable.mipmap_cache, &buf, id, DT_MIPMAP_FULL, DT_MIPMAP_BLOCKING);
      if(!buf.buf)
      {
        dt_control_log(_("file has unknown format!"));
      }
      else
      {
        dt_mipmap_cache_read_release(darktable.mipmap_cache, &buf);
        DT_CTL_SET_GLOBAL(lib_image_mouse_over_id, id);
        dt_ctl_switch_mode_to(DT_DEVELOP);
      }
    }
  }
  gtk_widget_destroy (filechooser);
  gtk_widget_queue_draw(dt_ui_center(darktable.gui->ui));
}
Exemplo n.º 27
0
bool mdk_dict::load(const std::string& ifofilename)
{
    if (! load_ifo(ifofilename.c_str()))
        return false;

    std::string fullfilename(ifofilename);
    fullfilename.replace(fullfilename.length() - sizeof("ifo") + 1, 
                         sizeof("ifo") - 1, "dict.dz");

    if (g_file_test(fullfilename.c_str(), G_FILE_TEST_EXISTS))
    {
        char extract_cmd[256];

        sprintf(extract_cmd, "/usr/bin/gunzip -S .dz %s", fullfilename.c_str());
        system(extract_cmd);
    }

    fullfilename.erase(fullfilename.length() - sizeof(".dz") + 1, 
                       sizeof(".dz") - 1);

    dictfile = fopen(fullfilename.c_str(), "rb");
    if (! dictfile)
    {
        g_print("open file %s failed!\n", fullfilename.c_str());
        return false;
    }

    fullfilename = ifofilename;
    fullfilename.replace(fullfilename.length() - sizeof("ifo")+1, 
                         sizeof("ifo") - 1, "idx.gz");

    if (! g_file_test(fullfilename.c_str(), G_FILE_TEST_EXISTS))
        fullfilename.erase(fullfilename.length() - sizeof(".gz") + 1, 
                           sizeof(".gz") - 1);

    index = new mdk_index();
    if (! index->load(fullfilename.c_str(), wordcount, index_file_size))
        return false;

    bool has_res = false;
    gchar *dirname = g_path_get_dirname(ifofilename.c_str());
    fullfilename = dirname;
    fullfilename += G_DIR_SEPARATOR_S "res";
    if (g_file_test(fullfilename.c_str(), G_FILE_TEST_IS_DIR))
    {
        has_res = true;
    } else {
        fullfilename = dirname;
        fullfilename += G_DIR_SEPARATOR_S "res.rifo";
        if (g_file_test(fullfilename.c_str(), G_FILE_TEST_EXISTS))
        {
            has_res = true;
        }
    }

    if (has_res)
    {
        storage = new ResourceStorage();
        bool failed = storage->load(dirname);
        if (failed) {
            delete storage;
            storage = NULL;
        }
    }
    g_free(dirname);

    return true;
}
Exemplo n.º 28
0
static void write_entry( FILE* of, GMenuTreeEntry* item )
{
    const char* cstr;
    char* str;
    int flags = 0;

//    if( gmenu_tree_entry_get_is_nodisplay(item) /* || gmenu_tree_entry_get_is_excluded(item) */ )
//        return;

    /* dekstop id, not necessarily the same as file basename */
    fprintf( of, "-%s\n", gmenu_tree_entry_get_desktop_file_id( item ) );

    /* Name */
    fprintf( of, "%s\n", gmenu_tree_entry_get_name( item ) );

    /* Comment */
    cstr = gmenu_tree_entry_get_comment( item );
    fprintf( of, "%s\n", cstr ? cstr : "" );

    /* Icon */
    cstr = gmenu_tree_entry_get_icon( item );
    fprintf( of, "%s\n", cstr ? cstr : "" );

    /* file dir/basename */
    if( gmenu_tree_entry_get_desktop_file_path( item ) )
    {
        /* file basenames are the same as desktop ids, except that sometimes
         * the '/' in paths are replaced with '-'.
         * for ex, /usr/share/applications/foo/bar.desktop has the app dir
         * /usr/share/applications, the filename foo/bar.desltop, and the
         * desktop id: foo-bar.desktop
         */

        /* filename */
        str = g_path_get_basename( gmenu_tree_entry_get_desktop_file_path( item ) );
        if( strcmp(str, gmenu_tree_entry_get_desktop_file_id(item) ) )
            fprintf( of, "%s\n", str );
        else
            fprintf( of, "\n" );
        g_free( str );

        /* dirname */
        str = g_path_get_dirname( gmenu_tree_entry_get_desktop_file_path( item ) );
        fprintf( of, "%d\n", dirname_index( str) );
        g_free( str );
    }
    else
    {
        fprintf( of, "\n-1\n" );
    }

    /* DisplayName */
    cstr = gmenu_tree_entry_get_display_name( item );
    fprintf( of, "%s\n", cstr ? cstr : "" );

    /* Exec */
    fprintf( of, "%s\n", gmenu_tree_entry_get_exec( item ) );

    /* Terminal/StartupNotify flags */
    if( gmenu_tree_entry_get_launch_in_terminal( item ) )
        flags |= FLAG_USE_TERMINAL;
    if( gmenu_tree_entry_get_use_startup_notify( item ) )
        flags |= FLAG_USE_SN;
    if( gmenu_tree_entry_get_is_nodisplay( item ) )
        flags |= FLAG_IS_NODISPLAY;
    fprintf( of, "%u\n", flags );

    /* ShowIn info */
    fprintf( of, "%d\n", gmenu_tree_entry_get_show_in_flags(item) );
/*
    if( gmenu_tree_entry_get_desktop_file_path( item ) )
        write_item_ex_info(of, gmenu_tree_entry_get_desktop_file_path( item ));
    fputs( "\n", of );
*/

}
Exemplo n.º 29
0
static gpointer
extract_thread (gpointer user_data)
{
	GList *args = (GList *) user_data;
	const char *savedir = (const char *) g_list_nth_data (args, 0);
	GList *files = (GList *) g_list_nth_data (args, 1);
	GList *indices = (GList *) g_list_nth_data (args, 2);

	GList *l, *f, *dirs = NULL;
	char *dir;
	unsigned long failed = 0, max = 0;
	gboolean stop = FALSE;
	GTimer *timer = NULL;

	g_list_free (args);


	/* Generate a list of unique subdirectories */
	for (l = files; l; l = l->next) {
		char *p;

		/* Convert paths to Unix paths */
		for (p = (char *) l->data; *p; p++) if (*p == '\\') *p = G_DIR_SEPARATOR;

		dir = g_path_get_dirname ((gchar *) l->data);
		if (!g_list_find_custom (dirs, dir, (GCompareFunc) g_ascii_strcasecmp)) {
			dirs = g_list_prepend (dirs, dir);
			max++;
		} else
			g_free (dir);
	}

	g_static_mutex_lock (&extractProgressM);
	extractProgress.max = max;
	extractProgress.status = STATUS_MKDIR;
	g_static_mutex_unlock (&extractProgressM);

	/* Create the subdirectories */
	dirs = g_list_sort (dirs, (GCompareFunc) g_ascii_strcasecmp);
	dirs = g_list_reverse (dirs);
	for (l = dirs; l; l = l->next) {
		dir = g_build_filename (G_DIR_SEPARATOR_S, savedir, (char *) l->data, NULL);
		mkdirs (dir);
		g_free (dir);

		g_static_mutex_lock (&extractProgressM);
		extractProgress.current++;
		stop = extractProgress.stop;
		g_static_mutex_unlock (&extractProgressM);
	}

	g_list_foreach (dirs, (GFunc) g_free, NULL);
	g_list_free (dirs);
	if (stop) goto end;


	g_static_mutex_lock (&extractProgressM);
	extractProgress.current = 0;
	extractProgress.max = g_list_length (files);
	extractProgress.status = STATUS_EXTRACT;
	stop = extractProgress.stop;
	g_static_mutex_unlock (&extractProgressM);

	if (stop) goto end;
	timer = g_timer_new ();
	g_timer_start (timer);

	/* Start the actual extraction */
	for (l = indices, f = files; l; l = l->next, f = f->next) {
		unsigned long i;
		char *fname;

		i = GPOINTER_TO_INT (l->data);
		fname = g_build_filename (savedir, (char *) f->data, NULL);
		if (!grf_index_extract (document.grf, i, fname, NULL))
			failed++;
		g_free (fname);

		g_static_mutex_lock (&extractProgressM);
		extractProgress.current++;
		strncpy (extractProgress.file, document.grf->files[i].name, PATH_MAX - 1);
		stop = extractProgress.stop;
		g_static_mutex_unlock (&extractProgressM);

		if (stop) goto end;
	}


	end:
	if (timer)
		g_timer_destroy (timer);
	g_list_free (files);
	g_list_free (indices);

	g_static_mutex_lock (&extractProgressM);
	extractProgress.failed = failed;
	extractProgress.status = STATUS_DONE;
	g_static_mutex_unlock (&extractProgressM);

	return NULL;
}
Exemplo n.º 30
0
static gchar*
parse_libtool_archive (const gchar* libtool_name)
{
  const guint TOKEN_DLNAME = G_TOKEN_LAST + 1;
  const guint TOKEN_INSTALLED = G_TOKEN_LAST + 2;
  const guint TOKEN_LIBDIR = G_TOKEN_LAST + 3;
  gchar *lt_dlname = NULL;
  gboolean lt_installed = TRUE;
  gchar *lt_libdir = NULL;
  gchar *name;
  GTokenType token;
  GScanner *scanner;
  
  int fd = g_open (libtool_name, O_RDONLY, 0);
  if (fd < 0)
    {
      gchar *display_libtool_name = g_filename_display_name (libtool_name);
      g_module_set_error_unduped (g_strdup_printf ("failed to open libtool archive \"%s\"", display_libtool_name));
      g_free (display_libtool_name);
      return NULL;
    }
  /* search libtool's dlname specification  */
  scanner = g_scanner_new (NULL);
  g_scanner_input_file (scanner, fd);
  scanner->config->symbol_2_token = TRUE;
  g_scanner_scope_add_symbol (scanner, 0, "dlname", 
			      GUINT_TO_POINTER (TOKEN_DLNAME));
  g_scanner_scope_add_symbol (scanner, 0, "installed", 
			      GUINT_TO_POINTER (TOKEN_INSTALLED));
  g_scanner_scope_add_symbol (scanner, 0, "libdir", 
			      GUINT_TO_POINTER (TOKEN_LIBDIR));
  while (!g_scanner_eof (scanner))
    {
      token = g_scanner_get_next_token (scanner);
      if (token == TOKEN_DLNAME || token == TOKEN_INSTALLED || 
	  token == TOKEN_LIBDIR)
	{
	  if (g_scanner_get_next_token (scanner) != '=' ||
	      g_scanner_get_next_token (scanner) != 
	      (token == TOKEN_INSTALLED ? 
	       G_TOKEN_IDENTIFIER : G_TOKEN_STRING))
	    {
	      gchar *display_libtool_name = g_filename_display_name (libtool_name);
	      g_module_set_error_unduped (g_strdup_printf ("unable to parse libtool archive \"%s\"", display_libtool_name));
	      g_free (display_libtool_name);

	      g_free (lt_dlname);
	      g_free (lt_libdir);
	      g_scanner_destroy (scanner);
	      close (fd);

	      return NULL;
	    }
	  else
	    {
	      if (token == TOKEN_DLNAME)
		{
		  g_free (lt_dlname);
		  lt_dlname = g_strdup (scanner->value.v_string);
		}
	      else if (token == TOKEN_INSTALLED)
		lt_installed = 
		  strcmp (scanner->value.v_identifier, "yes") == 0;
	      else /* token == TOKEN_LIBDIR */
		{
		  g_free (lt_libdir);
		  lt_libdir = g_strdup (scanner->value.v_string);
		}
	    }
	}      
    }

  if (!lt_installed)
    {
      gchar *dir = g_path_get_dirname (libtool_name);
      g_free (lt_libdir);
      lt_libdir = g_strconcat (dir, G_DIR_SEPARATOR_S ".libs", NULL);
      g_free (dir);
    }

  name = g_strconcat (lt_libdir, G_DIR_SEPARATOR_S, lt_dlname, NULL);
  
  g_free (lt_dlname);
  g_free (lt_libdir);
  g_scanner_destroy (scanner);
  close (fd);

  return name;
}