Example #1
0
int AP_Win32App::WinMain(const char * szAppName, HINSTANCE hInstance, 
						 HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
	if (!g_thread_supported ())
		g_thread_init (NULL);	
	
	bool bShowApp = true;
	BOOL bInitialized = FALSE; 
	
	// this is a static function and doesn't have a 'this' pointer.
	MSG msg;

#ifdef _MSC_VER
	_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_DEBUG );
	_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_DEBUG );
	_CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_WNDW);
#endif

	// HACK: load least-common-denominator Rich Edit control
	// TODO: fix Spell dlg so we don't rely on this
	// ALT:  make it a Preview widget instead

	HINSTANCE hinstRich = LoadLibraryW(L"riched32.dll");
	if (!hinstRich)
		hinstRich = LoadLibraryW(L"riched20.dll");
	UT_return_val_if_fail (hinstRich, 1);
	
	AP_Win32App * pMyWin32App;

	// OLE Stuff
	if (SUCCEEDED(OleInitialize(NULL)))
            bInitialized = TRUE;                    
  
	
// We put this in a block to force the destruction of Args in the stack
{
	UT_Win32LocaleString scnv;
	UT_UTF8String sUTFCmdLine;

	// Load the command line into an XAP_Args class
	scnv.fromLocale(GetCommandLineW());
	sUTFCmdLine=scnv.utf8_str();
	XAP_Args XArgs = XAP_Args(sUTFCmdLine.utf8_str());

	// Step 1: Initialize our application.
	pMyWin32App = new AP_Win32App(hInstance, szAppName);
	AP_Args Args = AP_Args(&XArgs, szAppName, pMyWin32App);

	Args.parseOptions();
	pMyWin32App->initialize();
  
	// Step 2: Handle all non-window args.
	// process args (calls common arg handler, which then calls platform specific)
	// As best I understand, it returns true to continue and show window, or
	// false if no window should be shown (and thus we should simply exit).    
	bool windowlessArgsWereSuccessful = true;
	if (!Args.doWindowlessArgs(windowlessArgsWereSuccessful))
	{
		pMyWin32App->shutdown();	// properly shutdown the app 1st
		delete pMyWin32App;
		return (windowlessArgsWereSuccessful ? 0 : -1);
	}

	// Step 3: Create windows as appropriate.
	// if some args are botched, it returns false and we should
	// continue out the door.
	// We used to check for bShowApp here.  It shouldn't be needed
	// anymore, because doWindowlessArgs was supposed to bail already. -PL
	if (!pMyWin32App->openCmdLineFiles(&Args))
	{
		pMyWin32App->shutdown();	// properly shutdown the app 1st
		delete pMyWin32App;
		return 0;
	}
}
//
// This block is controlled by the Structured Exception Handle
// if any crash happens here we will recover it and save the file (cross fingers)
//	


try
{		
	UT_uint32 iHeight = 0, iWidth = 0, t_flag =0;
	UT_sint32 iPosX = 0, iPosY = 0;
		
	if (!((XAP_App::getApp()->getGeometry(&iPosX,&iPosY,&iWidth,&iHeight,&t_flag)) &&
	       ((iWidth > 0) && (iHeight > 0)))	)
		XAP_App::getApp()->getDefaultGeometry(iWidth,iHeight,t_flag);
	
	if ((t_flag & PREF_FLAG_GEOMETRY_MAXIMIZED)==PREF_FLAG_GEOMETRY_MAXIMIZED)
			iCmdShow = SW_SHOWMAXIMIZED;
	
	if (bShowApp)
	{
		// display the windows
		for(UT_sint32 i = 0; i < pMyWin32App->m_vecFrames.getItemCount(); i++)
		{
			AP_Win32Frame * curFrame = (AP_Win32Frame*)pMyWin32App->m_vecFrames[i];
			UT_continue_if_fail(curFrame);
		
			HWND hwnd = curFrame->getTopLevelWindow();
			ShowWindow(hwnd, iCmdShow);
			UpdateWindow(hwnd);
		}	

		// do dispatch loop
		while(UT_GetMessage(&msg, NULL, 0, 0))
	    {
   	      	// TranslateMessage is not called because AbiWord
	      	// has its own way of decoding keyboard accelerators
	      	if (pMyWin32App->handleModelessDialogMessage(&msg)) 
				continue;
				
			TranslateMessage(&msg);	
			UT_DispatchMessage(&msg);
	    	
			// Check for idle condition
			while( !UT_Win32Idle::_isEmpty() &&
                   !PeekMessageW(&msg, NULL, 0, 0, PM_NOREMOVE) ) 
			{
				// Fire idle functions when no pending messages
		    	UT_Win32Idle::_fireall();
			}
	    }
	}
	
	// Un-init OLE		               
        if (bInitialized)
                OleUninitialize();

	FreeLibrary(hinstRich);

	// unload all loaded plugins (remove some of the memory leaks shown at shutdown :-)
	XAP_ModuleManager::instance().unloadAllPlugins();
	
	// Step 4: Destroy the App.  It should take care of deleting all frames.
	pMyWin32App->shutdown();
	delete pMyWin32App;
	
	
}// end of thes block is controlled by the Exception Handler

//
// If an exception happens, with "catch" the block
// and then the save it into disk
//
catch (...)
{
#ifdef DEBUG
	throw;
#endif

	AP_Win32App *pApp = (AP_Win32App *) XAP_App::getApp();
	
	UT_return_val_if_fail (pApp,1);

	// first of all, try to save the current prefs (so that any log entries are dumped
	// onto disk -- this allows us to save useful info for dbg purposes) we will enclose
	// this inside of a try/catch block, so that in the (unlikely) case something goes
	// badly wrong when writing the prefs file, we still get chance to save the open
	// documents

	try
	{
		if(pApp->getPrefs())
		{
			pApp->getPrefs()->savePrefsFile();
		}
	}
	catch(...)
	{
		// do nothing
	}
	
	IEFileType abiType = IE_Imp::fileTypeForSuffix(".abw");
	for (UT_sint32 i = 0; i < pApp->m_vecFrames.getItemCount(); i++)
	{
		AP_Win32Frame * curFrame = (AP_Win32Frame*)pApp->m_vecFrames[i];
		UT_continue_if_fail(curFrame);

		// again, we want to catch any exception thrown while saving individual documents,
		// in order to run through the whole loop
		try
		{
			if (NULL == curFrame->getFilename())
				curFrame->backup(".abw.saved", abiType);
			else
				curFrame->backup(".saved", abiType);
		}
		catch(...)
		{
			// do nothing
		}
	}	

	// Tell the user was has just happened
	AP_Win32Frame * curFrame = (AP_Win32Frame*)pApp->m_vecFrames[0];
	if (curFrame)
	{
		curFrame->showMessageBox(AP_STRING_ID_MSG_Exception,XAP_Dialog_MessageBox::b_O, XAP_Dialog_MessageBox::a_OK);
		
	}
}// end of except

	SET_CRT_DEBUG_FIELD( _CRTDBG_LEAK_CHECK_DF );
	return msg.wParam;
}
Example #2
0
int main(int argc, char *argv[])
{
    struct stat buf = { 0 };
    struct mntent *mnt = NULL;
    FILE *fp = NULL;
    gchar *uri;
    gint fileindex = 1;
    GError *error = NULL;
    GOptionContext *context;
    gint i;
    gdouble volume = 100.0;
    gchar *accelerator_keys;
    gchar **parse;
#ifdef GTK3_ENABLED
    GtkSettings *gtk_settings;
#endif
    int stat_result;

#ifndef OS_WIN32
    struct sigaction sa;
#endif
    gboolean playiter = FALSE;

#ifdef GIO_ENABLED
    GFile *file;
#endif

#ifdef ENABLE_NLS
    bindtextdomain(GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR);
    bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
    textdomain(GETTEXT_PACKAGE);
#endif

    playlist = 0;
    embed_window = 0;
    control_id = 0;
    window_x = 0;
    window_y = 0;
    last_window_width = 0;
    last_window_height = 0;
    showcontrols = 1;
    showsubtitles = TRUE;
    autostart = 1;
    videopresent = 0;
    disable_context_menu = FALSE;
    dontplaynext = FALSE;
    idledata = (IdleData *) g_new0(IdleData, 1);
    idledata->videopresent = FALSE;
    idledata->length = 0.0;
    idledata->device = NULL;
    idledata->cachepercent = -1.0;
    selection = NULL;
    path = NULL;
    js_state = STATE_UNDEFINED;
    control_instance = TRUE;
    playlistname = NULL;
    rpconsole = NULL;
    subtitle = NULL;
    tv_device = NULL;
    tv_driver = NULL;
    tv_width = 0;
    tv_height = 0;
    tv_fps = 0;
    ok_to_play = TRUE;
    alang = NULL;
    slang = NULL;
    metadata_codepage = NULL;
    playlistname = NULL;
    window_width = -1;
    window_height = -1;
    stored_window_width = -1;
    stored_window_height = -1;
    cache_size = 0;
    forcecache = FALSE;
    use_volume_option = FALSE;
    vertical_layout = FALSE;
    playlist_visible = FALSE;
    disable_fullscreen = FALSE;
    disable_framedrop = FALSE;
    softvol = FALSE;
    remember_softvol = FALSE;
    volume_softvol = -1;
    volume_gain = 0;
    subtitlefont = NULL;
    subtitle_codepage = NULL;
    subtitle_color = NULL;
    subtitle_outline = FALSE;
    subtitle_shadow = FALSE;
    subtitle_fuzziness = 0;
    disable_embeddedfonts = FALSE;
    quit_on_complete = FALSE;
    verbose = 0;
    reallyverbose = 0;
    embedding_disabled = FALSE;
    disable_pause_on_click = FALSE;
    disable_animation = FALSE;
    auto_hide_timeout = 3;
    mouse_over_controls = FALSE;
    use_mediakeys = TRUE;
    use_defaultpl = FALSE;
    mplayer_bin = NULL;
    mplayer_dvd_device = NULL;
    single_instance = FALSE;
    disable_deinterlace = TRUE;
    details_visible = FALSE;
    replace_and_play = FALSE;
    bring_to_front = FALSE;
    keep_on_top = FALSE;
    resize_on_new_media = FALSE;
    use_pausing_keep_force = FALSE;
    show_notification = TRUE;
    show_status_icon = TRUE;
    lang_group = NULL;
    audio_group = NULL;
    gpod_mount_point = NULL;
    load_tracks_from_gpod = FALSE;
    disable_cover_art_fetch = FALSE;
    fullscreen = 0;
    vo = NULL;
    data = NULL;
    max_data = NULL;
    details_table = NULL;
    large_buttons = FALSE;
    button_size = GTK_ICON_SIZE_BUTTON;
    lastguistate = -1;
    non_fs_height = 0;
    non_fs_width = 0;
    use_hw_audio = FALSE;
    start_second = 0;
    play_length = 0;
    save_loc = TRUE;
    use_xscrnsaver = FALSE;
    screensaver_disabled = FALSE;
    update_control_flag = FALSE;
    gchar *filename;
    skip_fixed_allocation_on_show = FALSE;
    skip_fixed_allocation_on_hide = FALSE;
    pref_volume = -1;
    use_mplayer2 = FALSE;
    enable_global_menu = FALSE;

#ifndef OS_WIN32
    sa.sa_handler = hup_handler;
    sigemptyset(&sa.sa_mask);
#ifdef SA_RESTART
    sa.sa_flags = SA_RESTART;   /* Restart functions if
                                   interrupted by handler */
#endif
#ifdef SIGINT
    if (sigaction(SIGINT, &sa, NULL) == -1)
        printf("SIGINT signal handler not installed\n");
#endif
#ifdef SIGHUP
    if (sigaction(SIGHUP, &sa, NULL) == -1)
        printf("SIGHUP signal handler not installed\n");
#endif
#ifdef SIGTERM
    if (sigaction(SIGTERM, &sa, NULL) == -1)
        printf("SIGTERM signal handler not installed\n");
#endif
#endif

    // call g_type_init or otherwise we can crash
    gtk_init(&argc, &argv);
    if (!g_thread_supported())
        g_thread_init(NULL);

    uri = g_strdup_printf("%s/gnome-mplayer/cover_art", g_get_user_config_dir());
    if (!g_file_test(uri, G_FILE_TEST_IS_DIR)) {
        g_mkdir_with_parents(uri, 0775);
    }
    g_free(uri);

    uri = g_strdup_printf("%s/gnome-mplayer/plugin", g_get_user_config_dir());
    if (!g_file_test(uri, G_FILE_TEST_IS_DIR)) {
        g_mkdir_with_parents(uri, 0775);
    }
    g_free(uri);
    uri = NULL;

    default_playlist = g_strdup_printf("file://%s/gnome-mplayer/default.pls", g_get_user_config_dir());
    safe_to_save_default_playlist = TRUE;

    gm_store = gm_pref_store_new("gnome-mplayer");
    gmp_store = gm_pref_store_new("gecko-mediaplayer");
    vo = gm_pref_store_get_string(gm_store, VO);
    audio_device.alsa_mixer = gm_pref_store_get_string(gm_store, ALSA_MIXER);
    use_hardware_codecs = gm_pref_store_get_boolean(gm_store, USE_HARDWARE_CODECS);
    use_crystalhd_codecs = gm_pref_store_get_boolean(gm_store, USE_CRYSTALHD_CODECS);
    osdlevel = gm_pref_store_get_int(gm_store, OSDLEVEL);
    pplevel = gm_pref_store_get_int(gm_store, PPLEVEL);
#ifndef HAVE_ASOUNDLIB
    volume = gm_pref_store_get_int(gm_store, VOLUME);
#endif
    audio_channels = gm_pref_store_get_int(gm_store, AUDIO_CHANNELS);
    use_hw_audio = gm_pref_store_get_boolean(gm_store, USE_HW_AUDIO);
    fullscreen = gm_pref_store_get_boolean(gm_store, FULLSCREEN);
    softvol = gm_pref_store_get_boolean(gm_store, SOFTVOL);
    remember_softvol = gm_pref_store_get_boolean(gm_store, REMEMBER_SOFTVOL);
    volume_softvol = gm_pref_store_get_float(gm_store, VOLUME_SOFTVOL);
    volume_gain = gm_pref_store_get_int(gm_store, VOLUME_GAIN);
    forcecache = gm_pref_store_get_boolean(gm_store, FORCECACHE);
    vertical_layout = gm_pref_store_get_boolean(gm_store, VERTICAL);
    playlist_visible = gm_pref_store_get_boolean(gm_store, SHOWPLAYLIST);
    details_visible = gm_pref_store_get_boolean(gm_store, SHOWDETAILS);
    show_notification = gm_pref_store_get_boolean(gm_store, SHOW_NOTIFICATION);
    show_status_icon = gm_pref_store_get_boolean(gm_store, SHOW_STATUS_ICON);
    showcontrols = gm_pref_store_get_boolean_with_default(gm_store, SHOW_CONTROLS, showcontrols);
    restore_controls = showcontrols;
    disable_deinterlace = gm_pref_store_get_boolean(gm_store, DISABLEDEINTERLACE);
    disable_framedrop = gm_pref_store_get_boolean(gm_store, DISABLEFRAMEDROP);
    disable_fullscreen = gm_pref_store_get_boolean(gm_store, DISABLEFULLSCREEN);
    disable_context_menu = gm_pref_store_get_boolean(gm_store, DISABLECONTEXTMENU);
    disable_ass = gm_pref_store_get_boolean(gm_store, DISABLEASS);
    disable_embeddedfonts = gm_pref_store_get_boolean(gm_store, DISABLEEMBEDDEDFONTS);
    disable_pause_on_click = gm_pref_store_get_boolean(gm_store, DISABLEPAUSEONCLICK);
    disable_animation = gm_pref_store_get_boolean(gm_store, DISABLEANIMATION);
    auto_hide_timeout = gm_pref_store_get_int_with_default(gm_store, AUTOHIDETIMEOUT, auto_hide_timeout);
    disable_cover_art_fetch = gm_pref_store_get_boolean(gm_store, DISABLE_COVER_ART_FETCH);
    use_mediakeys = gm_pref_store_get_boolean_with_default(gm_store, USE_MEDIAKEYS, use_mediakeys);
    use_defaultpl = gm_pref_store_get_boolean_with_default(gm_store, USE_DEFAULTPL, use_defaultpl);
    metadata_codepage = gm_pref_store_get_string(gm_store, METADATACODEPAGE);

    alang = gm_pref_store_get_string(gm_store, AUDIO_LANG);
    slang = gm_pref_store_get_string(gm_store, SUBTITLE_LANG);

    subtitlefont = gm_pref_store_get_string(gm_store, SUBTITLEFONT);
    subtitle_scale = gm_pref_store_get_float(gm_store, SUBTITLESCALE);
    if (subtitle_scale < 0.25) {
        subtitle_scale = 1.0;
    }
    subtitle_codepage = gm_pref_store_get_string(gm_store, SUBTITLECODEPAGE);
    subtitle_color = gm_pref_store_get_string(gm_store, SUBTITLECOLOR);
    subtitle_outline = gm_pref_store_get_boolean(gm_store, SUBTITLEOUTLINE);
    subtitle_shadow = gm_pref_store_get_boolean(gm_store, SUBTITLESHADOW);
    subtitle_margin = gm_pref_store_get_int(gm_store, SUBTITLE_MARGIN);
    subtitle_fuzziness = gm_pref_store_get_int(gm_store, SUBTITLE_FUZZINESS);
    showsubtitles = gm_pref_store_get_boolean_with_default(gm_store, SHOW_SUBTITLES, TRUE);

    qt_disabled = gm_pref_store_get_boolean(gmp_store, DISABLE_QT);
    real_disabled = gm_pref_store_get_boolean(gmp_store, DISABLE_REAL);
    wmp_disabled = gm_pref_store_get_boolean(gmp_store, DISABLE_WMP);
    dvx_disabled = gm_pref_store_get_boolean(gmp_store, DISABLE_DVX);
    midi_disabled = gm_pref_store_get_boolean(gmp_store, DISABLE_MIDI);
    embedding_disabled = gm_pref_store_get_boolean(gmp_store, DISABLE_EMBEDDING);
    disable_embedded_scaling = gm_pref_store_get_boolean(gmp_store, DISABLE_EMBEDDED_SCALING);
    if (embed_window == 0) {
        single_instance = gm_pref_store_get_boolean(gm_store, SINGLE_INSTANCE);
        if (single_instance) {
            replace_and_play = gm_pref_store_get_boolean(gm_store, REPLACE_AND_PLAY);
            bring_to_front = gm_pref_store_get_boolean(gm_store, BRING_TO_FRONT);
        }
    }
    enable_global_menu = gm_pref_store_get_boolean(gm_store, ENABLE_GLOBAL_MENU);
    if (!enable_global_menu) {
        enable_global_menu = (g_getenv("UBUNTU_MENUPROXY") == NULL ? FALSE : TRUE);
    }

    enable_nautilus_plugin = gm_pref_store_get_boolean_with_default(gm_store, ENABLE_NAUTILUS_PLUGIN, TRUE);

    mplayer_bin = gm_pref_store_get_string(gm_store, MPLAYER_BIN);
    if (mplayer_bin != NULL && !g_file_test(mplayer_bin, G_FILE_TEST_EXISTS)) {
        g_free(mplayer_bin);
        mplayer_bin = NULL;
    }
    mplayer_dvd_device = gm_pref_store_get_string(gm_store, MPLAYER_DVD_DEVICE);
    extraopts = gm_pref_store_get_string(gm_store, EXTRAOPTS);
    use_xscrnsaver = gm_pref_store_get_boolean_with_default(gm_store, USE_XSCRNSAVER, use_xscrnsaver);

    accelerator_keys = gm_pref_store_get_string(gm_store, ACCELERATOR_KEYS);
    accel_keys = g_strv_new(KEY_COUNT);
    accel_keys_description = g_strv_new(KEY_COUNT);
    if (accelerator_keys != NULL) {
        parse = g_strsplit(accelerator_keys, " ", KEY_COUNT);
        for (i = 0; i < g_strv_length(parse); i++) {
            accel_keys[i] = g_strdup(parse[i]);
        }
        g_free(accelerator_keys);
        g_strfreev(parse);
    }
    assign_default_keys();
    accel_keys_description[FILE_OPEN_LOCATION] = g_strdup(_("Open Location"));
    accel_keys_description[EDIT_SCREENSHOT] = g_strdup(_("Take Screenshot"));
    accel_keys_description[EDIT_PREFERENCES] = g_strdup(_("Preferences"));
    accel_keys_description[VIEW_PLAYLIST] = g_strdup(_("Playlist"));
    accel_keys_description[VIEW_INFO] = g_strdup(_("Media Info"));
    accel_keys_description[VIEW_DETAILS] = g_strdup(_("Details"));
    accel_keys_description[VIEW_METER] = g_strdup(_("Audio Meter"));
    accel_keys_description[VIEW_FULLSCREEN] = g_strdup(_("Full Screen"));
    accel_keys_description[VIEW_ASPECT] = g_strdup(_("Aspect"));
    accel_keys_description[VIEW_SUBTITLES] = g_strdup(_("Subtitles"));
    accel_keys_description[VIEW_DECREASE_SIZE] = g_strdup(_("Decrease Subtitle Size"));
    accel_keys_description[VIEW_INCREASE_SIZE] = g_strdup(_("Increase Subtitle Size"));
    accel_keys_description[VIEW_ANGLE] = g_strdup(_("Switch Angle"));
    accel_keys_description[VIEW_CONTROLS] = g_strdup(_("Controls"));

    remember_loc = gm_pref_store_get_boolean(gm_store, REMEMBER_LOC);
    loc_window_x = gm_pref_store_get_int(gm_store, WINDOW_X);
    loc_window_y = gm_pref_store_get_int(gm_store, WINDOW_Y);
    loc_window_height = gm_pref_store_get_int(gm_store, WINDOW_HEIGHT);
    loc_window_width = gm_pref_store_get_int(gm_store, WINDOW_WIDTH);
    loc_panel_position = gm_pref_store_get_int(gm_store, PANEL_POSITION);

    keep_on_top = gm_pref_store_get_boolean(gm_store, KEEP_ON_TOP);
    resize_on_new_media = gm_pref_store_get_boolean(gm_store, RESIZE_ON_NEW_MEDIA);
    mouse_wheel_changes_volume = gm_pref_store_get_boolean_with_default(gm_store, MOUSE_WHEEL_CHANGES_VOLUME, FALSE);

    audio_device_name = gm_pref_store_get_string(gm_store, AUDIO_DEVICE_NAME);
    audio_device.description = g_strdup(audio_device_name);

    context = g_option_context_new(_("[FILES...] - GNOME Media player based on MPlayer"));
#ifdef GTK2_12_ENABLED
    g_option_context_set_translation_domain(context, "UTF-8");
    g_option_context_set_translate_func(context, (GTranslateFunc) gettext, NULL, NULL);
#endif
    g_option_context_add_main_entries(context, entries, GETTEXT_PACKAGE);
    g_option_context_add_group(context, gtk_get_option_group(TRUE));
    g_option_context_parse(context, &argc, &argv, &error);
    g_option_context_free(context);

    if (new_instance)
        single_instance = FALSE;

    if (verbose == 0)
        verbose = gm_pref_store_get_int(gm_store, VERBOSE);

    if (reallyverbose)
        verbose = 2;

    if (verbose) {
        printf(_("GNOME MPlayer v%s\n"), VERSION);
        printf(_("gmtk v%s\n"), gmtk_version());
    }

    if (cache_size == 0)
        cache_size = gm_pref_store_get_int(gm_store, CACHE_SIZE);
    if (cache_size == 0)
        cache_size = 2000;

    plugin_audio_cache_size = gm_pref_store_get_int(gm_store, PLUGIN_AUDIO_CACHE_SIZE);
    if (plugin_audio_cache_size == 0)
        plugin_audio_cache_size = 2000;

    plugin_video_cache_size = gm_pref_store_get_int(gm_store, PLUGIN_VIDEO_CACHE_SIZE);
    if (plugin_video_cache_size == 0)
        plugin_video_cache_size = 2000;

    if (control_id != 0)
        cache_size = plugin_video_cache_size;

    gm_pref_store_free(gm_store);
    gm_pref_store_free(gmp_store);

    if (verbose && embed_window) {
        printf("embedded in window id 0x%x\n", embed_window);
    }

    if (verbose && single_instance) {
        printf("Running in single instance mode\n");
    }
#ifdef GIO_ENABLED
    if (verbose) {
        printf("Running with GIO support\n");
    }
#endif
#ifdef ENABLE_PANSCAN
    if (verbose) {
        printf("Running with panscan enabled (mplayer svn r29565 or higher required)\n");
    }
#endif
    if (verbose) {
        printf("Using audio device: %s\n", audio_device_name);
    }

    if (softvol) {
        if (verbose)
            printf("Using MPlayer Software Volume control\n");
        if (remember_softvol && volume_softvol != -1) {
            if (verbose)
                printf("Using last volume of %f%%\n", volume_softvol * 100.0);
            volume = (gdouble) volume_softvol *100.0;
        } else {
            volume = 100.0;
        }
    }

    if (large_buttons)
        button_size = GTK_ICON_SIZE_DIALOG;

    if (playlist_visible && control_id != 0)
        playlist_visible = FALSE;

    if (error != NULL) {
        printf("%s\n", error->message);
        printf(_("Run 'gnome-mplayer --help' to see a full list of available command line options.\n"));
        return 1;
    }
    // if (verbose)
    //      printf("Threading support enabled = %i\n",g_thread_supported());

    if (rpconsole == NULL)
        rpconsole = g_strdup("NONE");

    // setup playliststore
    playliststore =
        gtk_list_store_new(N_COLUMNS, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT,
                           G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_FLOAT, G_TYPE_STRING,
                           G_TYPE_STRING, G_TYPE_POINTER, G_TYPE_STRING, G_TYPE_STRING,
                           G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT, G_TYPE_INT, G_TYPE_INT,
                           G_TYPE_FLOAT, G_TYPE_FLOAT, G_TYPE_BOOLEAN);

    // only use dark theme if not embedded, otherwise use the default theme  
#ifdef GTK3_ENABLED
    if (embed_window <= 0) {
        gtk_settings = gtk_settings_get_default();
        g_object_set(G_OBJECT(gtk_settings), "gtk-application-prefer-dark-theme", TRUE, NULL);
    }
#endif

    create_window(embed_window);

    autopause = FALSE;
#ifdef GIO_ENABLED
    idledata->caching = g_mutex_new();
    idledata->caching_complete = g_cond_new();
#endif

    retrieve_metadata_pool = g_thread_pool_new(retrieve_metadata, NULL, 10, TRUE, NULL);

    if (argv[fileindex] != NULL) {
#ifdef GIO_ENABLED
        file = g_file_new_for_commandline_arg(argv[fileindex]);
        stat_result = -1;
        if (file != NULL) {
            GError *error = NULL;
            GFileInfo *file_info = g_file_query_info(file, G_FILE_ATTRIBUTE_UNIX_MODE, 0, NULL, &error);
            if (file_info != NULL) {
                buf.st_mode = g_file_info_get_attribute_uint32(file_info, G_FILE_ATTRIBUTE_UNIX_MODE);
                stat_result = 0;
                g_object_unref(file_info);
            }
            if (error != NULL) {
                if (verbose)
                    printf("failed to get mode: %s\n", error->message);
                g_error_free(error);
            }
            g_object_unref(file);
        }
#else
        stat_result = g_stat(argv[fileindex], &buf);
#endif

        if (verbose) {
            printf("opening %s\n", argv[fileindex]);
            printf("stat_result = %i\n", stat_result);
            printf("is block %i\n", S_ISBLK(buf.st_mode));
            printf("is character %i\n", S_ISCHR(buf.st_mode));
            printf("is reg %i\n", S_ISREG(buf.st_mode));
            printf("is dir %i\n", S_ISDIR(buf.st_mode));
            printf("playlist %i\n", playlist);
            printf("embedded in window id 0x%x\n", embed_window);
        }
        if (stat_result == 0 && S_ISBLK(buf.st_mode)) {
            // might have a block device, so could be a DVD

#ifdef HAVE_SYS_MOUNT_H
            fp = setmntent("/etc/mtab", "r");
            do {
                mnt = getmntent(fp);
                if (mnt)
                    printf("%s is at %s\n", mnt->mnt_fsname, mnt->mnt_dir);
                if (argv[fileindex] != NULL && mnt && mnt->mnt_fsname != NULL) {
                    if (strcmp(argv[fileindex], mnt->mnt_fsname) == 0)
                        break;
                }
            }
            while (mnt);
            endmntent(fp);
#endif
            if (mnt && mnt->mnt_dir) {
                printf("%s is mounted on %s\n", argv[fileindex], mnt->mnt_dir);
                uri = g_strdup_printf("%s/VIDEO_TS", mnt->mnt_dir);
                stat(uri, &buf);
                g_free(uri);
                if (S_ISDIR(buf.st_mode)) {
                    add_item_to_playlist("dvdnav://", 0);
                    gtk_tree_model_get_iter_first(GTK_TREE_MODEL(playliststore), &iter);
                    gmtk_media_player_set_media_type(GMTK_MEDIA_PLAYER(media), TYPE_DVD);
                    //play_iter(&iter, 0);
                    playiter = TRUE;
                } else {
                    uri = g_strdup_printf("file://%s", mnt->mnt_dir);
                    create_folder_progress_window();
                    add_folder_to_playlist_callback(uri, NULL);
                    g_free(uri);
                    destroy_folder_progress_window();
                    if (random_order) {
                        gtk_tree_model_get_iter_first(GTK_TREE_MODEL(playliststore), &iter);
                        randomize_playlist(playliststore);
                    }
                    if (gtk_tree_model_get_iter_first(GTK_TREE_MODEL(playliststore), &iter)) {
                        // play_iter(&iter, 0);
                        playiter = TRUE;
                    }
                }
            } else {
                parse_cdda("cdda://");
                if (random_order) {
                    gtk_tree_model_get_iter_first(GTK_TREE_MODEL(playliststore), &iter);
                    randomize_playlist(playliststore);
                }
                //play_file("cdda://", playlist);
                if (gtk_tree_model_get_iter_first(GTK_TREE_MODEL(playliststore), &iter)) {
                    // play_iter(&iter, 0);
                    playiter = TRUE;
                }
            }
        } else if (stat_result == 0 && S_ISDIR(buf.st_mode)) {
            uri = g_strdup_printf("%s/VIDEO_TS", argv[fileindex]);
            stat_result = g_stat(uri, &buf);
            g_free(uri);
            if (stat_result == 0 && S_ISDIR(buf.st_mode)) {
                add_item_to_playlist("dvdnav://", 0);
                gtk_tree_model_get_iter_first(GTK_TREE_MODEL(playliststore), &iter);
                gmtk_media_player_set_media_type(GMTK_MEDIA_PLAYER(media), TYPE_DVD);
                //play_iter(&iter, 0);
                playiter = TRUE;
            } else {
                create_folder_progress_window();
                uri = NULL;
#ifdef GIO_ENABLED
                file = g_file_new_for_commandline_arg(argv[fileindex]);
                if (file != NULL) {
                    uri = g_file_get_uri(file);
                    g_object_unref(file);
                }
#else
                uri = g_filename_to_uri(argv[fileindex], NULL, NULL);
#endif
                add_folder_to_playlist_callback(uri, NULL);
                g_free(uri);
                destroy_folder_progress_window();
                if (random_order) {
                    gtk_tree_model_get_iter_first(GTK_TREE_MODEL(playliststore), &iter);
                    randomize_playlist(playliststore);
                }
                if (gtk_tree_model_get_iter_first(GTK_TREE_MODEL(playliststore), &iter)) {
                    //play_iter(&iter, 0);
                    playiter = TRUE;
                }
            }
        } else {
            // local file
            // detect if playlist here, so even if not specified it can be picked up
            i = fileindex;

            while (argv[i] != NULL) {
                if (verbose > 1)
                    printf("Argument %i is %s\n", i, argv[i]);
#ifdef GIO_ENABLED
                if (!device_name(argv[i])) {
                    file = g_file_new_for_commandline_arg(argv[i]);
                    if (file != NULL) {
                        uri = g_file_get_uri(file);
                        g_object_unref(file);
                    } else {
                        uri = g_strdup(argv[i]);
                    }
                } else {
                    uri = g_strdup(argv[i]);
                }
#else
                uri = g_filename_to_uri(argv[i], NULL, NULL);
#endif

                if (uri != NULL) {
                    if (playlist == 0)
                        playlist = detect_playlist(uri);
                    if (!playlist) {
                        add_item_to_playlist(uri, playlist);
                    } else {
                        if (!parse_playlist(uri)) {
                            add_item_to_playlist(uri, playlist);
                        }
                    }
                    g_free(uri);
                }
                i++;
            }

            if (random_order) {
                gtk_tree_model_get_iter_first(GTK_TREE_MODEL(playliststore), &iter);
                randomize_playlist(playliststore);
            }
            if (gtk_tree_model_get_iter_first(GTK_TREE_MODEL(playliststore), &iter)) {
                // play_iter(&iter, 0);
                playiter = TRUE;
            }
        }

    }
#ifdef HAVE_GPOD
    if (load_tracks_from_gpod) {
        gpod_mount_point = find_gpod_mount_point();
        printf("mount point is %s\n", gpod_mount_point);
        if (gpod_mount_point != NULL) {
            gpod_load_tracks(gpod_mount_point);
        } else {
            printf("Unable to find gpod mount point\n");
        }
    }
#endif

    gm_audio_update_device(&audio_device);
    gm_audio_get_volume(&audio_device);
    gm_audio_set_server_volume_update_callback(&audio_device, set_volume);
    set_media_player_attributes(media);

    if (!softvol) {
        if (pref_volume != -1) {
            audio_device.volume = (gdouble) pref_volume / 100.0;
        }
        if (verbose)
            printf("The volume on '%s' is %f\n", audio_device.description, audio_device.volume);
        volume = audio_device.volume * 100;
    } else {
        audio_device.volume = volume / 100.0;
    }
#ifdef GTK2_12_ENABLED
    gtk_scale_button_set_value(GTK_SCALE_BUTTON(vol_slider), audio_device.volume);
#else
    gtk_range_set_value(GTK_RANGE(vol_slider), audio_device.volume);
#endif
    use_volume_option = detect_volume_option();

    dbus_hookup(embed_window, control_id);
    show_window(embed_window);

    if (playiter)
        play_iter(&iter, 0);

    if (argv[fileindex] == NULL && embed_window == 0) {
        // When running as apple.com external player, don't load the default playlist
        if (control_id == 0) {
            use_remember_loc = remember_loc;
            gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem_view_playlist), playlist_visible);
        } else {
            remember_loc = FALSE;
            use_remember_loc = FALSE;
            // prevents saving of a playlist with one item on it
            use_defaultpl = FALSE;
            // don't save the loc when launched with a single file
            save_loc = FALSE;
        }
    } else {
        // prevents saving of a playlist with one item on it
        use_defaultpl = FALSE;
        // don't save the loc when launched with a single file
        save_loc = FALSE;
    }

    if (single_instance && embed_window == 0) {
        if (control_id == 0) {
            use_remember_loc = remember_loc;
            gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem_view_playlist), playlist_visible);
        }
    }

    if (embed_window == 0) {
        if (remember_loc) {
            gtk_window_move(GTK_WINDOW(window), loc_window_x, loc_window_y);
            g_idle_add(set_pane_position, NULL);

        }
    }

    safe_to_save_default_playlist = FALSE;
    if (use_defaultpl) {
        create_folder_progress_window();
        parse_playlist(default_playlist);
        destroy_folder_progress_window();
    }
    safe_to_save_default_playlist = TRUE;

    gtk_main();

    return 0;
}
Example #3
0
File: main.c Project: haobug/evince
int
main (int argc, char *argv[])
{
	GOptionContext *context;
	GError         *error = NULL;

#ifdef G_OS_WIN32

    if (fileno (stdout) != -1 &&
 	  _get_osfhandle (fileno (stdout)) != -1)
	{
	  /* stdout is fine, presumably redirected to a file or pipe */
	}
    else
    {
	  typedef BOOL (* WINAPI AttachConsole_t) (DWORD);

	  AttachConsole_t p_AttachConsole =
	    (AttachConsole_t) GetProcAddress (GetModuleHandle ("kernel32.dll"), "AttachConsole");

	  if (p_AttachConsole != NULL && p_AttachConsole (ATTACH_PARENT_PROCESS))
      {
	      freopen ("CONOUT$", "w", stdout);
	      dup2 (fileno (stdout), 1);
	      freopen ("CONOUT$", "w", stderr);
	      dup2 (fileno (stderr), 2);

      }
	}
#endif

#if (!GLIB_CHECK_VERSION(2,31,0))
/* Remove this once we bump dependencies to glib >= 2.31.0 */
	/* Init glib threads asap */
	if (!g_thread_supported ())
		g_thread_init (NULL);
#endif

#ifdef ENABLE_NLS
	/* Initialize the i18n stuff */
	bindtextdomain (GETTEXT_PACKAGE, ev_get_locale_dir());
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);
#endif

	context = g_option_context_new (N_("GNOME Document Viewer"));
	g_option_context_set_translation_domain(context, GETTEXT_PACKAGE);
	g_option_context_add_main_entries (context, goption_options, GETTEXT_PACKAGE);

#ifdef WITH_SMCLIENT
	g_option_context_add_group (context, egg_sm_client_get_option_group ());
#endif

	g_option_context_add_group (context, gtk_get_option_group (TRUE));

	if (!g_option_context_parse (context, &argc, &argv, &error)) {
		g_printerr ("Cannot parse arguments: %s\n", error->message);
		g_error_free (error);
		g_option_context_free (context);

		return 1;
	}
	g_option_context_free (context);

	if (preview_mode) {
		gboolean retval;
		
		retval = launch_previewer ();
		
		return retval ? 0 : 1;
	}

        if (!ev_init ())
                return 1;

	ev_stock_icons_init ();

#if defined(WITH_SMCLIENT) && defined(GDK_WINDOWING_X11)
	egg_set_desktop_file (GNOMEDATADIR "/applications/evince.desktop");
#else
	/* Manually set name and icon */
	g_set_application_name (_("Document Viewer"));
	gtk_window_set_default_icon_name ("evince");
#endif /* WITH_SMCLIENT && GDK_WINDOWING_X11 */

	ev_application_load_session (EV_APP);
	load_files (file_arguments);

	/* Change directory so we don't prevent unmounting in case the initial cwd
	 * is on an external device (see bug #575436)
	 */
	g_chdir (g_get_home_dir ());

	gtk_main ();

	ev_shutdown ();
	ev_stock_icons_shutdown ();

	return 0;
}
Example #4
0
static int MicrocodeDialog()
{
	GtkWidget *infoLabel;
	GtkWidget *infoFrame, *infoTable;
	GtkWidget *crcInfoLabel, *crcDataInfoLabel, *textInfoLabel;
	GtkWidget *crcLabel = NULL, *crcDataLabel = NULL, *textLabel = NULL;
	GtkWidget *selectUcodeLabel;
	//GtkWidget *microcodeLabel;
	GtkWidget *okButton, *stopButton;
	GList *ucodeList = 0;
	char buf[1024];

	if (!g_thread_supported())
		g_thread_init( NULL );
	gdk_threads_enter();

	// create dialog
	if (microcodeWindow == 0)
	{
		microcodeWindow = gtk_dialog_new();
		gtk_signal_connect( GTK_OBJECT(microcodeWindow), "delete_event",
		                    GTK_SIGNAL_FUNC(delete_question_event), (gpointer)NULL );
		sprintf( buf, "%s - unknown microcode", pluginName );
		gtk_window_set_title( GTK_WINDOW(microcodeWindow), buf );
		gtk_container_set_border_width( GTK_CONTAINER(GTK_DIALOG(microcodeWindow)->vbox), 11 );

		// ok button
		okButton = gtk_button_new_with_label( "Ok" );
		gtk_signal_connect_object( GTK_OBJECT(okButton), "clicked",
                               GTK_SIGNAL_FUNC(okButton_clicked), NULL );
		gtk_container_add( GTK_CONTAINER(GTK_DIALOG(microcodeWindow)->action_area), okButton );

		// stop button
		stopButton = gtk_button_new_with_label( "Stop" );
		gtk_signal_connect_object( GTK_OBJECT(stopButton), "clicked",
                               GTK_SIGNAL_FUNC(stopButton_clicked), NULL );
		gtk_container_add( GTK_CONTAINER(GTK_DIALOG(microcodeWindow)->action_area), stopButton );

		// info label
		infoLabel = gtk_label_new( "Unknown microcode. Please notify Orkin, including the following information:" );
		gtk_box_pack_start_defaults( GTK_BOX(GTK_DIALOG(microcodeWindow)->vbox), infoLabel );

		// info frame
		infoFrame = gtk_frame_new( "Microcode info" );
		gtk_container_set_border_width( GTK_CONTAINER(infoFrame), 7 );
		gtk_box_pack_start_defaults( GTK_BOX(GTK_DIALOG(microcodeWindow)->vbox), infoFrame );

		infoTable = gtk_table_new( 3, 2, FALSE );
		gtk_container_set_border_width( GTK_CONTAINER(infoTable), 7 );
		gtk_table_set_col_spacings( GTK_TABLE(infoTable), 3 );
		gtk_table_set_row_spacings( GTK_TABLE(infoTable), 3 );
		gtk_container_add( GTK_CONTAINER(infoFrame), infoTable );

		crcInfoLabel = gtk_label_new( "Microcode CRC:" );
		crcDataInfoLabel = gtk_label_new( "Microcode Data CRC:" );
		textInfoLabel = gtk_label_new( "Microcode Text:" );

		crcLabel = gtk_label_new( "" );
		crcDataLabel = gtk_label_new( "" );
		textLabel = gtk_label_new( "" );

		gtk_table_attach_defaults( GTK_TABLE(infoTable), crcInfoLabel, 0, 1, 0, 1 );
		gtk_table_attach_defaults( GTK_TABLE(infoTable), crcLabel, 1, 2, 0, 1 );
		gtk_table_attach_defaults( GTK_TABLE(infoTable), crcDataInfoLabel, 0, 1, 1, 2 );
		gtk_table_attach_defaults( GTK_TABLE(infoTable), crcDataLabel, 1, 2, 1, 2 );
		gtk_table_attach_defaults( GTK_TABLE(infoTable), textInfoLabel, 0, 1, 2, 3 );
		gtk_table_attach_defaults( GTK_TABLE(infoTable), textLabel, 1, 2, 2, 3 );

		selectUcodeLabel = gtk_label_new( "You can manually select the closest matching microcode." );
		for (int i = 0; i < numMicrocodeTypes; i++)
			ucodeList = g_list_append( ucodeList, gtk_list_item_new_with_label( MicrocodeTypes[i] ) );
		microcodeList = gtk_list_new();
		gtk_list_set_selection_mode( GTK_LIST(microcodeList), GTK_SELECTION_SINGLE );
		gtk_list_append_items( GTK_LIST(microcodeList), ucodeList );

		gtk_box_pack_start_defaults( GTK_BOX(GTK_DIALOG(microcodeWindow)->vbox), selectUcodeLabel );
		gtk_box_pack_start_defaults( GTK_BOX(GTK_DIALOG(microcodeWindow)->vbox), microcodeList );
	}

	snprintf( buf, 1024, "0x%8.8X", (unsigned int)uc_crc );
        if(crcLabel) gtk_label_set_text( GTK_LABEL(crcLabel), buf );
	snprintf( buf, 1024, "0x%8.8X", (unsigned int)uc_dcrc );
	if(crcDataLabel) gtk_label_set_text( GTK_LABEL(crcDataLabel), buf );
	if(textLabel) gtk_label_set_text( GTK_LABEL(textLabel), uc_str );

	selectedMicrocode = -1;
	gtk_widget_show_all( microcodeWindow );

	while (selectedMicrocode == -1)
	{
//		if( gtk_main_iteration() )
//			break;
		usleep( 10000 );
	}
	gdk_threads_leave();
	return selectedMicrocode;
}
Example #5
0
/**
 * Main entry point for sleepd - runs the initialization hooks installed at program load time
 *
 * A bit counter-intuitively, this is not the first part of this program which
 * is run.
 *
 * First, everything which uses the {@link INIT_FUNC} macro in init.h are run,
 * which registers a bunch of hooks with the initialization system so that
 * individual modules can be registered without touching the main sleepd
 * initialization code.  Then, once all of those hooks are installed, execution
 * proceeds to this function which actually runs those hooks.
 *
 * - Initializes sleepd.
 * - Attaches as a Luna service under com.palm.sleep.
 * - Attaches to Nyx.
 * - Subscribes to events related to the charger being plugged and unplugged from the com.palm.power service.
 * - Calls {@link TheOneInit()} to finish initialization of the service.
 * - Issues a request to the com.palm.power service to check on the plugged/unplugged status of the charger.
 *
 * @param   argc        Number of command-line arguments.
 * @param   argv        List of command-line arguments.
 *
 * @todo Move the logging initialization functionality into {@link TheOneInit()}.
 */
int
main(int argc, char **argv)
{
	bool retVal;

	/*
	 * Register a function to be able to gracefully handle termination signals
	 * from the OS or other processes.
	 */
	signal(SIGTERM, term_handler);
	signal(SIGINT, term_handler);

#if !GLIB_CHECK_VERSION(2,32,0)

	if (!g_thread_supported())
	{
		g_thread_init(NULL);
	}

#endif

	mainloop = g_main_loop_new(NULL, FALSE);

	/*
	 *  initialize the lunaservice and we want it before all the init
	 *  stuff happening.
	 */
	LSError lserror;
	LSErrorInit(&lserror);

	/*
	 * Register ourselves as the com.palm.sleep service.
	 */
	retVal = LSRegisterPalmService("com.palm.sleep", &psh, &lserror);

	if (retVal)
	{
		/*
		 * Attach our main loop to the service so we can process IPC messages addressed to us.
		 */
		retVal = LSGmainAttachPalmService(psh, mainloop, &lserror);

		if (retVal)
		{

			/*
			 * Get our private bus for our service so we can pass a message to com.palm.power.
			 */
			private_sh = LSPalmServiceGetPrivateConnection(psh);

			/*
			 * Register with com.palm.power for events regarding changes in status
			 * to the plug/unplug state of any chargers which may be attached to our
			 * device.
			 */
			retVal = LSCall(private_sh, "luna://com.palm.lunabus/signal/addmatch",
			                "{\"category\":\"/com/palm/power\","
			                "\"method\":\"USBDockStatus\"}", ChargerStatus, NULL, NULL, &lserror);

			if (retVal)
			{
				/*
				 * Connect to Nyx so we can use it later.
				 */
				int ret = nyx_device_open(NYX_DEVICE_SYSTEM, "Main", &nyxSystem);

				if (ret != NYX_ERROR_NONE)
				{
					SLEEPDLOG_CRITICAL(MSGID_NYX_DEVICE_OPEN_FAIL, 1,
					                   PMLOGKS(CAUSE, "Unable to open the nyx device system"), "");
					abort();
				}


				/*
				 * Call our main initialization function - this is the function which
				 * is supposed to handle initializing pretty much everything for us.
				 */
				TheOneInit();

				/*
				 * Now that we've got something listening for charger status changes,
				 * request the current state of the charger from com.palm.power.
				 */
				LSCall(private_sh, "luna://com.palm.power/com/palm/power/chargerStatusQuery",
				       "{}", ChargerStatus, NULL, NULL, &lserror);

				SLEEPDLOG_DEBUG("Sleepd daemon started");

				g_main_loop_run(mainloop);
			}
		}
	}
	else
	{
		SLEEPDLOG_CRITICAL(MSGID_SRVC_REGISTER_FAIL, 1, PMLOGKS(ERRTEXT,
		                   lserror.message), "Could not initialize sleepd");
		LSErrorFree(&lserror);
	}

	g_main_loop_unref(mainloop);
	return 0;
}
Example #6
0
int main(int argc, char **argv)
{
	GOptionContext *context;
	GError *err = NULL;
	DBusConnection *conn;
	DBusError error;
	guint signal;

#ifdef NEED_THREADS
	if (g_thread_supported() == FALSE)
		g_thread_init(NULL);
#endif

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

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

		g_printerr("An unknown error occurred\n");
		return 1;
	}

	g_option_context_free(context);

	if (option_version == TRUE) {
		printf("%s\n", VERSION);
		exit(0);
	}

	if (option_detach == TRUE) {
		if (daemon(0, 0)) {
			perror("Can't start daemon");
			return 1;
		}
	}

	event_loop = g_main_loop_new(NULL, FALSE);

#ifdef NEED_THREADS
	if (dbus_threads_init_default() == FALSE) {
		fprintf(stderr, "Can't init usage of threads\n");
		exit(1);
	}
#endif

	signal = setup_signalfd();

	__ofono_log_init(argv[0], option_debug, option_detach);

	dbus_error_init(&error);

	conn = g_dbus_setup_bus(DBUS_BUS_SYSTEM, OFONO_SERVICE, &error);
	if (conn == NULL) {
		if (dbus_error_is_set(&error) == TRUE) {
			ofono_error("Unable to hop onto D-Bus: %s",
					error.message);
			dbus_error_free(&error);
		} else {
			ofono_error("Unable to hop onto D-Bus");
		}

		goto cleanup;
	}

	g_dbus_set_disconnect_function(conn, system_bus_disconnected,
					NULL, NULL);

	__ofono_dbus_init(conn);

	__ofono_modemwatch_init();

	__ofono_manager_init();

	__ofono_plugin_init(option_plugin, option_noplugin);

	g_free(option_plugin);
	g_free(option_noplugin);

	g_main_loop_run(event_loop);

	__ofono_plugin_cleanup();

	__ofono_manager_cleanup();

	__ofono_modemwatch_cleanup();

	__ofono_dbus_cleanup();
	dbus_connection_unref(conn);

cleanup:
	g_source_remove(signal);

	g_main_loop_unref(event_loop);

	__ofono_log_cleanup();

	g_free(option_debug);

	return 0;
}
Example #7
0
static void
g_cancellable_class_init (GCancellableClass *klass)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);

  g_type_class_add_private (klass, sizeof (GCancellablePrivate));

  if (cancellable_cond == NULL && g_thread_supported ())
    cancellable_cond = g_cond_new ();
  
  gobject_class->finalize = g_cancellable_finalize;

  /**
   * GCancellable::cancelled:
   * @cancellable: a #GCancellable.
   * 
   * Emitted when the operation has been cancelled.
   * 
   * Can be used by implementations of cancellable operations. If the
   * operation is cancelled from another thread, the signal will be
   * emitted in the thread that cancelled the operation, not the
   * thread that is running the operation.
   *
   * Note that disconnecting from this signal (or any signal) in a
   * multi-threaded program is prone to race conditions. For instance
   * it is possible that a signal handler may be invoked even
   * <emphasis>after</emphasis> a call to
   * g_signal_handler_disconnect() for that handler has already
   * returned.
   * 
   * There is also a problem when cancellation happen
   * right before connecting to the signal. If this happens the
   * signal will unexpectedly not be emitted, and checking before
   * connecting to the signal leaves a race condition where this is
   * still happening.
   *
   * In order to make it safe and easy to connect handlers there
   * are two helper functions: g_cancellable_connect() and
   * g_cancellable_disconnect() which protect against problems
   * like this.
   *
   * An example of how to us this:
   * |[
   *     /<!-- -->* Make sure we don't do any unnecessary work if already cancelled *<!-- -->/
   *     if (g_cancellable_set_error_if_cancelled (cancellable))
   *       return;
   *
   *     /<!-- -->* Set up all the data needed to be able to
   *      * handle cancellation of the operation *<!-- -->/
   *     my_data = my_data_new (...);
   *
   *     id = 0;
   *     if (cancellable)
   *       id = g_cancellable_connect (cancellable,
   *     			      G_CALLBACK (cancelled_handler)
   *     			      data, NULL);
   *
   *     /<!-- -->* cancellable operation here... *<!-- -->/
   *
   *     g_cancellable_disconnect (cancellable, id);
   *
   *     /<!-- -->* cancelled_handler is never called after this, it
   *      * is now safe to free the data *<!-- -->/
   *     my_data_free (my_data);  
   * ]|
   *
   * Note that the cancelled signal is emitted in the thread that
   * the user cancelled from, which may be the main thread. So, the
   * cancellable signal should not do something that can block.
   */
  signals[CANCELLED] =
    g_signal_new (I_("cancelled"),
		  G_TYPE_FROM_CLASS (gobject_class),
		  G_SIGNAL_RUN_LAST,
		  G_STRUCT_OFFSET (GCancellableClass, cancelled),
		  NULL, NULL,
		  g_cclosure_marshal_VOID__VOID,
		  G_TYPE_NONE, 0);
  
}
Example #8
0
int
main (int argc, char **argv)
{
    static const GOptionEntry test_goptions[] = {
        {   "videosink", '\0', 0, G_OPTION_ARG_STRING, &opt_videosink_str,
            "videosink to use (default: " DEFAULT_VIDEOSINK ")", NULL
        },
        {   "caps", '\0', 0, G_OPTION_ARG_STRING, &opt_filtercaps_str,
            "filter caps to narrow down formats to test", NULL
        },
        {   "with-ffmpegcolorspace", '\0', 0, G_OPTION_ARG_NONE,
            &opt_with_ffmpegcolorspace,
            "whether to add an ffmpegcolorspace element in front of the sink",
            NULL
        },
        {NULL, '\0', 0, 0, NULL, NULL, NULL}
    };
    GOptionContext *ctx;
    GError *opt_err = NULL;

    GstElement *pipeline, *src, *filter1, *crop, *scale, *filter2, *csp, *sink;
    GMainLoop *loop;
    GstCaps *filter_caps = NULL;
    GList *caps_list, *l;

    if (!g_thread_supported ())
        g_thread_init (NULL);

    /* command line option parsing */
    ctx = g_option_context_new ("");
    g_option_context_add_group (ctx, gst_init_get_option_group ());
    g_option_context_add_main_entries (ctx, test_goptions, NULL);

    if (!g_option_context_parse (ctx, &argc, &argv, &opt_err)) {
        g_error ("Error parsing command line options: %s", opt_err->message);
        return -1;
    }

    GST_DEBUG_CATEGORY_INIT (videocrop_test_debug, "videocroptest", 0, "vctest");

    loop = g_main_loop_new (NULL, FALSE);

    pipeline = gst_pipeline_new ("pipeline");
    src = gst_element_factory_make ("videotestsrc", "videotestsrc");
    g_assert (src != NULL);
    filter1 = gst_element_factory_make ("capsfilter", "capsfilter1");
    g_assert (filter1 != NULL);
    crop = gst_element_factory_make ("videocrop", "videocrop");
    g_assert (crop != NULL);
    scale = gst_element_factory_make ("videoscale", "videoscale");
    g_assert (scale != NULL);
    filter2 = gst_element_factory_make ("capsfilter", "capsfilter2");
    g_assert (filter2 != NULL);

    if (opt_with_ffmpegcolorspace) {
        g_print ("Adding ffmpegcolorspace\n");
        csp = gst_element_factory_make ("ffmpegcolorspace", "colorspace");
    } else {
        csp = gst_element_factory_make ("identity", "colorspace");
    }
    g_assert (csp != NULL);

    if (opt_filtercaps_str) {
        filter_caps = gst_caps_from_string (opt_filtercaps_str);
        if (filter_caps == NULL) {
            g_error ("Invalid filter caps string '%s'", opt_filtercaps_str);
        } else {
            g_print ("Using filter caps '%s'\n", opt_filtercaps_str);
        }
    }

    if (opt_videosink_str) {
        g_print ("Trying videosink '%s' ...", opt_videosink_str);
        sink = gst_element_factory_make (opt_videosink_str, "sink");
        g_print ("%s\n", (sink) ? "ok" : "element couldn't be created");
    } else {
        sink = NULL;
    }

    if (sink == NULL) {
        g_print ("Trying videosink '%s' ...", DEFAULT_VIDEOSINK);
        sink = gst_element_factory_make (DEFAULT_VIDEOSINK, "sink");
        g_print ("%s\n", (sink) ? "ok" : "element couldn't be created");
    }
    if (sink == NULL) {
        g_print ("Trying videosink '%s' ...", "xvimagesink");
        sink = gst_element_factory_make ("xvimagesink", "sink");
        g_print ("%s\n", (sink) ? "ok" : "element couldn't be created");
    }
    if (sink == NULL) {
        g_print ("Trying videosink '%s' ...", "ximagesink");
        sink = gst_element_factory_make ("ximagesink", "sink");
        g_print ("%s\n", (sink) ? "ok" : "element couldn't be created");
    }

    g_assert (sink != NULL);

    gst_bin_add_many (GST_BIN (pipeline), src, filter1, crop, scale, filter2,
                      csp, sink, NULL);

    if (!gst_element_link (src, filter1))
        g_error ("Failed to link videotestsrc to capsfilter1");

    if (!gst_element_link (filter1, crop))
        g_error ("Failed to link capsfilter1 to videocrop");

    if (!gst_element_link (crop, scale))
        g_error ("Failed to link videocrop to videoscale");

    if (!gst_element_link (scale, filter2))
        g_error ("Failed to link videoscale to capsfilter2");

    if (!gst_element_link (filter2, csp))
        g_error ("Failed to link capsfilter2 to ffmpegcolorspace");

    if (!gst_element_link (csp, sink))
        g_error ("Failed to link ffmpegcolorspace to video sink");

    caps_list = video_crop_get_test_caps (crop);
    for (l = caps_list; l != NULL; l = l->next) {
        GstStateChangeReturn ret;
        GstCaps *caps, *out_caps;
        gboolean skip = FALSE;
        gchar *s;

        if (filter_caps) {
            GstCaps *icaps;

            icaps = gst_caps_intersect (filter_caps, GST_CAPS (l->data));
            skip = gst_caps_is_empty (icaps);
            gst_caps_unref (icaps);
        }

        /* this is the size of our window (stays fixed) */
        out_caps = gst_caps_copy (GST_CAPS (l->data));
        gst_structure_set (gst_caps_get_structure (out_caps, 0), "width",
                           G_TYPE_INT, OUT_WIDTH, "height", G_TYPE_INT, OUT_HEIGHT, NULL);

        g_object_set (filter2, "caps", out_caps, NULL);

        /* filter1 gets these too to prevent videotestsrc from renegotiating */
        g_object_set (filter1, "caps", out_caps, NULL);
        gst_caps_unref (out_caps);

        caps = gst_caps_copy (GST_CAPS (l->data));
        GST_INFO ("testing format: %" GST_PTR_FORMAT, caps);

        s = gst_caps_to_string (caps);

        if (skip) {
            g_print ("Skipping format: %s\n", s);
            g_free (s);
            continue;
        }

        g_print ("Format: %s\n", s);

        caps = gst_caps_make_writable (caps);

        /* FIXME: check return values */
        ret = gst_element_set_state (pipeline, GST_STATE_PLAYING);
        if (ret != GST_STATE_CHANGE_FAILURE) {
            ret = gst_element_get_state (pipeline, NULL, NULL, -1);

            if (ret != GST_STATE_CHANGE_FAILURE) {
                test_with_caps (src, crop, caps);
            } else {
                g_print ("Format: %s not supported (failed to go to PLAYING)\n", s);
            }
        } else {
            g_print ("Format: %s not supported\n", s);
        }

        gst_element_set_state (pipeline, GST_STATE_NULL);

        gst_caps_unref (caps);
        g_free (s);
    }

    g_list_foreach (caps_list, (GFunc) gst_caps_unref, NULL);
    g_list_free (caps_list);

    gst_element_set_state (pipeline, GST_STATE_NULL);
    gst_object_unref (pipeline);

    return 0;
}
Example #9
0
static void
run (const gchar         *name,
     gint                 nparams,
     const GimpParam     *param,
     gint                *nreturn_vals,
     GimpParam          **return_vals)
{
  static GimpParam   values[1];
  GimpRunMode        run_mode;
  GimpPDBStatusType  status;
  //gint32           image_ID;
  gint32             drawable_ID;
  FblurParam        *fblur_param;

  /* Get the specified values */
  run_mode    = param[0].data.d_int32;
  //image_ID    = param[1].data.d_image;
  drawable_ID = param[2].data.d_drawable;

#ifdef ENABLE_MP
  if (! g_thread_supported ())
    g_thread_init (NULL);
#endif

  INIT_I18N ();

  /* Check image type */
  if (! gimp_drawable_is_rgb (drawable_ID) &&
      ! gimp_drawable_is_gray (drawable_ID))
    {
      status = GIMP_PDB_EXECUTION_ERROR;
      goto focusblur_exit;
    }

  /* Initialize parameters */
  fblur_param = focusblur_param_new (drawable_ID);
  if (! fblur_param)
    {
      status = GIMP_PDB_EXECUTION_ERROR;
      goto focusblur_exit;
    }

  switch (run_mode)
    {
    case GIMP_RUN_INTERACTIVE:
      /* Possibly retrieve data */
      focusblur_param_restore (fblur_param);

      /* Get information from the dialog */
      if (! focusblur_dialog (fblur_param))
        {
          status = GIMP_PDB_SUCCESS;
          goto focusblur_exit;
        }
      break;

    case GIMP_RUN_NONINTERACTIVE:
      /* Make sure all the arguments are present */
      if (! focusblur_param_set (fblur_param, nparams, param))
        {
          status = GIMP_PDB_CALLING_ERROR;
          goto focusblur_exit;
        }
      break;

    case GIMP_RUN_WITH_LAST_VALS:
      /* Possibly retrieve data */
      if (! focusblur_param_restore (fblur_param))
        {
          status = GIMP_PDB_CALLING_ERROR;
          goto focusblur_exit;
        }
      break;
    }

  if (focusblur_execute (fblur_param, NULL))
    status = GIMP_PDB_SUCCESS;
  else
    status = GIMP_PDB_EXECUTION_ERROR;

  /* If run mode is interactive, flush displays */
  if (run_mode != GIMP_RUN_NONINTERACTIVE)
    gimp_displays_flush ();

  /* Store data */
  if (run_mode == GIMP_RUN_INTERACTIVE)
    focusblur_param_store (fblur_param);

 focusblur_exit:

  if (run_mode == GIMP_RUN_INTERACTIVE)
    focusblur_rc_save_preferences (&(fblur_param->pref));

  focusblur_param_destroy (&fblur_param);
  values[0].type          = GIMP_PDB_STATUS;
  values[0].data.d_status = status;
  *nreturn_vals = G_N_ELEMENTS (values);
  *return_vals  = values;
}
Example #10
0
bool wxApp::Initialize(int& argc, wxChar **argv)
{
    bool init_result;

#if wxUSE_THREADS
    if (!g_thread_supported())
        g_thread_init(NULL);

    wxgs_poll_func = g_main_context_get_poll_func(NULL);
    g_main_context_set_poll_func(NULL, wxapp_poll_func);
#endif // wxUSE_THREADS

    gtk_set_locale();

    // We should have the wxUSE_WCHAR_T test on the _outside_
#if wxUSE_WCHAR_T
    // gtk+ 2.0 supports Unicode through UTF-8 strings
    wxConvCurrent = &wxConvUTF8;
#else // !wxUSE_WCHAR_T
    if (!wxOKlibc())
        wxConvCurrent = (wxMBConv*) NULL;
#endif // wxUSE_WCHAR_T/!wxUSE_WCHAR_T

    // decide which conversion to use for the file names

    // (1) this variable exists for the sole purpose of specifying the encoding
    //     of the filenames for GTK+ programs, so use it if it is set
    wxString encName(wxGetenv(_T("G_FILENAME_ENCODING")));
    encName = encName.BeforeFirst(_T(','));
    if (encName.CmpNoCase(_T("@locale")) == 0)
        encName.clear();
    encName.MakeUpper();
#if wxUSE_INTL
    if (encName.empty())
    {
        // (2) if a non default locale is set, assume that the user wants his
        //     filenames in this locale too
        encName = wxLocale::GetSystemEncodingName().Upper();
        // (3) finally use UTF-8 by default
        if (encName.empty() || encName == _T("US-ASCII"))
            encName = _T("UTF-8");
        wxSetEnv(_T("G_FILENAME_ENCODING"), encName);
    }
#else
    if (encName.empty())
        encName = _T("UTF-8");
#endif // wxUSE_INTL

#if wxUSE_WCHAR_T
    static wxConvBrokenFileNames fileconv(encName);
    wxConvFileName = &fileconv;
#endif // wxUSE_WCHAR_T

#if wxUSE_UNICODE
    // gtk_init() wants UTF-8, not wchar_t, so convert
    int i;
    char **argvGTK = new char *[argc + 1];
    for ( i = 0; i < argc; i++ )
    {
        argvGTK[i] = wxStrdupA(wxConvUTF8.cWX2MB(argv[i]));
    }

    argvGTK[argc] = NULL;

    int argcGTK = argc;

#ifdef __WXGPE__
    init_result = true;  // is there a _check() version of this?
    gpe_application_init( &argcGTK, &argvGTK );
#else
    init_result = gtk_init_check( &argcGTK, &argvGTK );
#endif

    if ( argcGTK != argc )
    {
        // we have to drop the parameters which were consumed by GTK+
        for ( i = 0; i < argcGTK; i++ )
        {
            while ( strcmp(wxConvUTF8.cWX2MB(argv[i]), argvGTK[i]) != 0 )
            {
                memmove(argv + i, argv + i + 1, (argc - i)*sizeof(*argv));
            }
        }

        argc = argcGTK;
    }
    //else: gtk_init() didn't modify our parameters

    // free our copy
    for ( i = 0; i < argcGTK; i++ )
    {
        free(argvGTK[i]);
    }

    delete [] argvGTK;
#else // !wxUSE_UNICODE
    // gtk_init() shouldn't actually change argv itself (just its contents) so
    // it's ok to pass pointer to it
    init_result = gtk_init_check( &argc, &argv );
#endif // wxUSE_UNICODE/!wxUSE_UNICODE

    if (!init_result) {
        wxLogError(wxT("Unable to initialize gtk, is DISPLAY set properly?"));
        return false;
    }

    // update internal arg[cv] as GTK+ may have removed processed options:
    this->argc = argc;
    this->argv = argv;

    // we can not enter threads before gtk_init is done
    gdk_threads_enter();

    if ( !wxAppBase::Initialize(argc, argv) )
    {
        gdk_threads_leave();

        return false;
    }

    wxSetDetectableAutoRepeat( true );

#if wxUSE_INTL
    wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
#endif

    return true;
}
Example #11
0
int main (int argc, char *argv[])
{
	int i;
	char *pluginname = NULL;
	char *plugindir = NULL;
	char *configfile = NULL;
	char *objtype = NULL;
	OSyncError *error = NULL;

	if (argc < 2)
		usage (argv[0], 1);

	pluginname = argv[1];
	for (i = 2; i < argc; i++) {
		char *arg = argv[i];
		if (!strcmp (arg, "--config")) {
			configfile = argv[i + 1];
			i++;
			if (!configfile)
				usage (argv[0], 1);
		} else if (!strcmp (arg, "--type")) {
			objtype = argv[i + 1];
			i++;
			if (!objtype)
				usage (argv[0], 1);
		} else if (!strcmp (arg, "--plugindir")) {
			printf("plugindir %s\n", argv[i + 1]);
			plugindir = argv[i + 1];
			i++;
			if (!plugindir)
				usage (argv[0], 1);
		} else if (!strcmp (arg, "--random")) {
			only_random = TRUE;
		} else if (!strcmp (arg, "--help")) {
			usage (argv[0], 0);
		} else {
			usage (argv[0], 1);
		}
	}

	OSyncEnv *env = osync_env_new(NULL);
	osync_env_set_option(env, "LOAD_GROUPS", "FALSE");

	if (plugindir)
		osync_env_set_option(env, "PLUGINS_DIRECTORY", plugindir);

	if (!osync_env_initialize(env, &error)) {
		printf("Unable to initialize environment: %s\n", osync_error_print(&error));
		osync_error_unref(&error);
		return 1;
	}

	char *testdir = g_strdup_printf("%s/plgtest.XXXXXX", g_get_tmp_dir());
	char *result = mkdtemp(testdir);

	if (result == NULL)
	{
		osync_trace(TRACE_EXIT_ERROR, "unable to create temporary dir: %s", g_strerror(errno));
		return 1;
	}

	OSyncGroup *group = osync_group_new(env);
	osync_group_set_name(group, osync_rand_str(8));
	osync_group_set_configdir(group, testdir);
	OSyncMember *member = osync_member_new(group);

	char *config = NULL;
	int size = 0;
	if (configfile) {
		if (!osync_file_read(configfile, &config, &size, &error)) {
			fprintf(stderr, "Unable to read config: %s\n", osync_error_print(&error));
			osync_error_unref(&error);
			return 1;
		}
		osync_member_set_config(member, config, size);
	}

	osync_member_set_pluginname(member, pluginname);

	OSyncMember *file = osync_member_new(group);

	localdir = g_strdup_printf("%s/plgtest.XXXXXX", g_get_tmp_dir());
	result = mkdtemp(localdir);

	if (result == NULL)
	{
		osync_trace(TRACE_EXIT_ERROR, "unable to create temporary dir: %s", g_strerror(errno));
		return 1;
	}

	config = g_strdup_printf("<config><path>%s</path><recursive>0</recursive></config>", localdir);
	osync_member_set_config(file, config, strlen(config) + 1);
	osync_member_set_pluginname(file, "file-sync");

	if (!osync_group_save(group, &error)) {
		printf("Error while creating syncengine: %s\n", osync_error_print(&error));
		osync_error_unref(&error);
		goto error_free_env;
	}

	if (!g_thread_supported ()) g_thread_init (NULL);

	OSyncEngine *engine = osengine_new(group, &error);
	if (!engine) {
		printf("Error while creating syncengine: %s\n", osync_error_print(&error));
		osync_error_unref(&error);
		goto error_free_env;
	}

	if (!osengine_init(engine, &error)) {
		printf("Error while initializing syncengine: %s\n", osync_error_print(&error));
		osync_error_unref(&error);
		goto error_free_engine;
	}

	int count = 0;
	if (only_random) {
		do {
			count++;
			printf("++++++++++++++++++++++++++++++\n");
			printf("Initializing new round #%i!\n", count);

			if (g_random_int_range(0, 5) == 0) {
				int i;
				OSyncFormatEnv *env = osync_group_get_format_env(group);
				for (i = 0; i < osync_conv_num_objtypes(env); i++) {
					if (g_random_int_range(0, 5) == 0) {
						OSyncObjType *type = osync_conv_nth_objtype(env, i);
						osync_group_set_slow_sync(group, osync_objtype_get_name(type), TRUE);
						printf("Requesting slow-sync for: %s\n", osync_objtype_get_name(type));
					}
				}
				osync_conv_env_free(env);
			}

			change_content();

			check_sync(engine, "Random", 1);
		} while (g_random_int_range(0, 3) != 0);

		printf("Finalizing engine\n");
		osengine_finalize(engine);
		osengine_free(engine);

		engine = osengine_new(group, &error);
		if (!engine) {
			printf("Error while creating syncengine: %s\n", osync_error_print(&error));
			osync_error_unref(&error);
			goto error_free_env;
		}

		if (!osengine_init(engine, &error)) {
			printf("Error while initializing syncengine: %s\n", osync_error_print(&error));
			osync_error_unref(&error);
			goto error_free_engine;
		}
	} else {
		register_tests();
		run_all_tests(engine, file, member, objtype);
	}

	printf("\nCompleted successfully\n");
	return 0;

error_free_engine:
	osengine_free(engine);
error_free_env:
	osync_group_free(group);
	osync_env_free(env);
	return 1;
}
Example #12
0
int
main (int argc, char *argv[])
{
	signal_user_data_t *ud;
	GValue *preset;
	GError *error = NULL;
	GOptionContext *context;

#ifdef ENABLE_NLS
	bindtextdomain (GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);
#endif

	if (!g_thread_supported())
		g_thread_init(NULL);
	context = g_option_context_new ("- Transcode media formats");
	g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
	g_option_context_add_group (context, gtk_get_option_group (TRUE));
#if defined(_ENABLE_GST)
	g_option_context_add_group (context, gst_init_get_option_group ());
#endif
	g_option_context_parse (context, &argc, &argv, &error);
	g_option_context_free(context);

	if (argc > 1 && dvd_device == NULL && argv[1][0] != '-')
	{
		dvd_device = argv[1];
	}
	
	gtk_init (&argc, &argv);
	gtk_rc_parse_string(hud_rcstyle);
	g_type_class_unref(g_type_class_ref(GTK_TYPE_BUTTON));
	g_object_set(gtk_settings_get_default(), "gtk-button-images", TRUE, NULL);
#if !defined(_WIN32)
	notify_init("HandBrake");
#endif
	ghb_register_transforms();
	ghb_resource_init();
	ghb_load_icons();

#if !defined(_WIN32)
	dbus_g_thread_init();
#endif
	ghb_udev_init();

	ghb_write_pid_file();
	ud = g_malloc0(sizeof(signal_user_data_t));
	ud->debug = ghb_debug;
	g_log_set_handler (NULL, G_LOG_LEVEL_DEBUG, debug_log_handler, ud);
	g_log_set_handler ("Gtk", G_LOG_LEVEL_WARNING, warn_log_handler, ud);
	//g_log_set_handler ("Gtk", G_LOG_LEVEL_CRITICAL, warn_log_handler, ud);
	ud->settings = ghb_settings_new();
	ud->builder = create_builder_or_die (BUILDER_NAME);
	// Enable events that alert us to media change events
	watch_volumes (ud);

	//GtkWidget *widget = GHB_WIDGET(ud->builder, "PictureDetelecineCustom");
	//gtk_entry_set_inner_border(widget, 2);

	// Since GtkBuilder no longer assigns object ids to widget names
	// Assign a few that are necessary for style overrides to work
	GtkWidget *widget;
#if defined(_NO_UPDATE_CHECK)
	widget = GHB_WIDGET(ud->builder, "check_updates_box");
	gtk_widget_hide(widget);
#endif

	widget = GHB_WIDGET(ud->builder, "preview_hud");
	gtk_widget_set_name(widget, "preview_hud");
	widget = GHB_WIDGET(ud->builder, "preview_window");
	gtk_widget_set_name(widget, "preview_window");

	// Set up the "hud" control overlay for the preview window
	GtkWidget *draw, *hud, *blender, *align;

	align = GHB_WIDGET(ud->builder, "preview_window_alignment");
	draw = GHB_WIDGET(ud->builder, "preview_image_align");
	hud = GHB_WIDGET(ud->builder, "preview_hud");

	// Set up compositing for hud
	blender = ghb_compositor_new();

	gtk_container_add(GTK_CONTAINER(align), blender);
	ghb_compositor_zlist_insert(GHB_COMPOSITOR(blender), draw, 1, 1);
	ghb_compositor_zlist_insert(GHB_COMPOSITOR(blender), hud, 2, .85);
	gtk_widget_show(blender);

	// Redirect stderr to the activity window
	ghb_preview_init(ud);
	IoRedirect(ud);
	ghb_log( "%s - %s - %s",
		HB_PROJECT_TITLE, HB_PROJECT_BUILD_TITLE, HB_PROJECT_URL_WEBSITE );
	ghb_init_dep_map();

	// Need to connect x264_options textview buffer to the changed signal
	// since it can't be done automatically
	GtkTextView *textview;
	GtkTextBuffer *buffer;
	textview = GTK_TEXT_VIEW(GHB_WIDGET (ud->builder, "x264Option"));
	buffer = gtk_text_view_get_buffer (textview);
	g_signal_connect(buffer, "changed", (GCallback)x264_entry_changed_cb, ud);

	ghb_combo_init(ud);

	g_debug("ud %p\n", ud);
	g_debug("ud->builder %p\n", ud->builder);

	bind_audio_tree_model(ud);
	bind_subtitle_tree_model(ud);
	bind_presets_tree_model(ud);
	bind_queue_tree_model(ud);
	bind_chapter_tree_model(ud);
	// Connect up the signals to their callbacks
	// I wrote my own connector so that I could pass user data
	// to the callbacks.  Builder's standard autoconnect doesn't all this.
	gtk_builder_connect_signals_full (ud->builder, MyConnect, ud);

	// Load all internal settings
	ghb_settings_init(ud);
	// Load the presets files
	ghb_presets_load(ud);
	ghb_prefs_load(ud);

	ghb_prefs_to_ui(ud);

	gint logLevel;
	logLevel = ghb_settings_get_int(ud->settings, "LoggingLevel");
	ghb_backend_init(logLevel);

	if (ghb_settings_get_boolean(ud->settings, "hbfd"))
	{
		ghb_hbfd(ud, TRUE);
	}
	gchar *source = ghb_settings_get_string(ud->settings, "default_source");
	ghb_dvd_set_current(source, ud);
	g_free(source);

	// Parsing x264 options "" initializes x264 widgets to proper defaults
	ghb_x264_parse_options(ud, "");

	// Populate the presets tree view
	ghb_presets_list_init(ud, NULL, 0);
	// Get the first preset name
	if (arg_preset != NULL)
	{
		preset = ghb_parse_preset_path(arg_preset);
		if (preset)
		{
			ghb_select_preset(ud->builder, preset);
			ghb_value_free(preset);
		}
	}
	else
	{
		ghb_select_default_preset(ud->builder);
	}

	// Grey out widgets that are dependent on a disabled feature
	ghb_check_all_depencencies (ud);

	if (dvd_device != NULL)
	{
		// Source overridden from command line option
		ghb_settings_set_string(ud->settings, "scan_source", dvd_device);
		g_idle_add((GSourceFunc)ghb_idle_scan, ud);
	}
	// Reload and check status of the last saved queue
	g_idle_add((GSourceFunc)ghb_reload_queue, ud);

	// Start timer for monitoring libhb status, 500ms
	g_timeout_add (500, ghb_timer_cb, (gpointer)ud);

	// Add dvd devices to File menu
	ghb_volname_cache_init();
	g_thread_create((GThreadFunc)ghb_cache_volnames, ud, FALSE, NULL);

#if defined(_USE_APP_IND)
	GtkUIManager * uim = GTK_UI_MANAGER(GHB_OBJECT(ud->builder, "uimanager1"));

	GtkMenu *ai_menu = GTK_MENU(gtk_ui_manager_get_widget(uim, "/ui/tray_menu"));
	ud->ai = app_indicator_new("HandBrake", "hb-icon", APP_INDICATOR_CATEGORY_APPLICATION_STATUS);
	app_indicator_set_menu( ud->ai, ai_menu );
	app_indicator_set_label( ud->ai, "", "99.99%");
	if (ghb_settings_get_boolean(ud->settings, "show_status"))
	{
		app_indicator_set_status( ud->ai, APP_INDICATOR_STATUS_ACTIVE );
	}
	else
	{
		app_indicator_set_status( ud->ai, APP_INDICATOR_STATUS_PASSIVE );
	}
	GtkStatusIcon *si;
	si = GTK_STATUS_ICON(GHB_OBJECT(ud->builder, "hb_status"));

	gtk_status_icon_set_visible(si, FALSE );
#else
	GtkStatusIcon *si;
	si = GTK_STATUS_ICON(GHB_OBJECT(ud->builder, "hb_status"));

	gtk_status_icon_set_visible(si,
			ghb_settings_get_boolean(ud->settings, "show_status"));

#if GTK_CHECK_VERSION(2, 16, 0)
	gtk_status_icon_set_has_tooltip(si, TRUE);
	g_signal_connect(si, "query-tooltip", 
					status_icon_query_tooltip_cb, ud);
#else
	gtk_status_icon_set_tooltip(si, "HandBrake");
#endif
#endif

	// Ugly hack to keep subtitle table from bouncing around as I change
	// which set of controls are visible
	GtkRequisition req;
	gint width, height;
	
	widget = GHB_WIDGET(ud->builder, "SrtCodeset");
	gtk_widget_size_request( widget, &req );
	height = req.height;
	widget = GHB_WIDGET(ud->builder, "srt_code_label");
	gtk_widget_size_request( widget, &req );
	height += req.height;
	widget = GHB_WIDGET(ud->builder, "subtitle_table");
	gtk_widget_set_size_request(widget, -1, height);
	
	widget = GHB_WIDGET (ud->builder, "hb_window");

	GdkGeometry geo = { 
		-1, -1, 1024, 768, -1, -1, 10, 10, 0, 0, GDK_GRAVITY_NORTH_WEST
	};
	GdkWindowHints geo_mask;
	geo_mask = GDK_HINT_MIN_SIZE | GDK_HINT_MAX_SIZE | GDK_HINT_BASE_SIZE;
	gtk_window_set_geometry_hints( GTK_WINDOW(widget), widget, &geo, geo_mask);
	width = ghb_settings_get_int(ud->settings, "window_width");
	height = ghb_settings_get_int(ud->settings, "window_height");
	gtk_window_resize(GTK_WINDOW(widget), width, height);
	gtk_widget_show(widget);

	/*
 	 * Filter objects in GtkBuilder xml
 	 * Unfortunately, GtkFilter is poorly supported by GtkBuilder,
 	 * so a lot of the setup must happen in code.
		SourceFilterAll
		SourceFilterVideo
		SourceFilterTS
		SourceFilterMPG
		SourceFilterEVO
		SourceFilterVOB
		SourceFilterMKV
		SourceFilterMP4
		SourceFilterAVI
		SourceFilterMOV
		SourceFilterOGG
		SourceFilterFLV
		SourceFilterWMV
	*/
	// Add filters to source chooser
	GtkFileFilter *filter;
	GtkFileChooser *chooser;
	chooser = GTK_FILE_CHOOSER(GHB_WIDGET(ud->builder, "source_dialog"));
	filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterAll"));
	gtk_file_filter_set_name(filter, "All");
	gtk_file_filter_add_pattern(filter, "*");
	gtk_file_chooser_add_filter(chooser, filter);
	filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterVideo"));
	gtk_file_filter_set_name(filter, "Video");
	gtk_file_filter_add_mime_type(filter, "video/*");
	gtk_file_chooser_add_filter(chooser, filter);
	filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterTS"));
	gtk_file_filter_set_name(filter, "TS");
	gtk_file_filter_add_pattern(filter, "*.ts");
	gtk_file_filter_add_pattern(filter, "*.TS");
	gtk_file_filter_add_pattern(filter, "*.m2ts");
	gtk_file_filter_add_pattern(filter, "*.M2TS");
	gtk_file_chooser_add_filter(chooser, filter);
	filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterMPG"));
	gtk_file_filter_set_name(filter, "MPG");
	gtk_file_filter_add_pattern(filter, "*.mpg");
	gtk_file_filter_add_pattern(filter, "*.MPG");
	gtk_file_filter_add_pattern(filter, "*.mepg");
	gtk_file_filter_add_pattern(filter, "*.MEPG");
	gtk_file_chooser_add_filter(chooser, filter);
	filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterEVO"));
	gtk_file_filter_set_name(filter, "EVO");
	gtk_file_filter_add_pattern(filter, "*.evo");
	gtk_file_filter_add_pattern(filter, "*.EVO");
	gtk_file_chooser_add_filter(chooser, filter);
	filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterVOB"));
	gtk_file_filter_set_name(filter, "VOB");
	gtk_file_filter_add_pattern(filter, "*.vob");
	gtk_file_filter_add_pattern(filter, "*.VOB");
	gtk_file_chooser_add_filter(chooser, filter);
	filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterMKV"));
	gtk_file_filter_set_name(filter, "MKV");
	gtk_file_filter_add_pattern(filter, "*.mkv");
	gtk_file_filter_add_pattern(filter, "*.MKV");
	gtk_file_chooser_add_filter(chooser, filter);
	filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterMP4"));
	gtk_file_filter_set_name(filter, "MP4");
	gtk_file_filter_add_pattern(filter, "*.mp4");
	gtk_file_filter_add_pattern(filter, "*.MP4");
	gtk_file_filter_add_pattern(filter, "*.m4v");
	gtk_file_filter_add_pattern(filter, "*.M4V");
	gtk_file_chooser_add_filter(chooser, filter);
	filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterMOV"));
	gtk_file_filter_set_name(filter, "MOV");
	gtk_file_filter_add_pattern(filter, "*.mov");
	gtk_file_filter_add_pattern(filter, "*.MOV");
	gtk_file_chooser_add_filter(chooser, filter);
	filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterAVI"));
	gtk_file_filter_set_name(filter, "AVI");
	gtk_file_filter_add_pattern(filter, "*.avi");
	gtk_file_filter_add_pattern(filter, "*.AVI");
	gtk_file_chooser_add_filter(chooser, filter);
	filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterOGG"));
	gtk_file_filter_set_name(filter, "OGG");
	gtk_file_filter_add_pattern(filter, "*.ogg");
	gtk_file_filter_add_pattern(filter, "*.OGG");
	gtk_file_filter_add_pattern(filter, "*.ogv");
	gtk_file_filter_add_pattern(filter, "*.OGV");
	gtk_file_filter_add_pattern(filter, "*.ogm");
	gtk_file_filter_add_pattern(filter, "*.OGM");
	gtk_file_chooser_add_filter(chooser, filter);
	filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterFLV"));
	gtk_file_filter_set_name(filter, "FLV");
	gtk_file_filter_add_pattern(filter, "*.flv");
	gtk_file_filter_add_pattern(filter, "*.FLV");
	gtk_file_chooser_add_filter(chooser, filter);
	filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterWMV"));
	gtk_file_filter_set_name(filter, "WMV");
	gtk_file_filter_add_pattern(filter, "*.wmv");
	gtk_file_filter_add_pattern(filter, "*.WMV");
	gtk_file_chooser_add_filter(chooser, filter);

	// Gtk has a really stupid bug.  If the file chooser is showing
	// hidden files AND there is no filter set, it will not select
	// the filename when gtk_file_chooser_set_filename is called.
	// So add a completely unnessary filter to prevent this behavior.
	filter = GTK_FILE_FILTER(GHB_OBJECT(ud->builder, "SourceFilterAll"));
	gtk_file_chooser_set_filter(chooser, filter);

	PangoFontDescription *font_desc;
	font_desc = pango_font_description_from_string ("monospace 10");
	textview = GTK_TEXT_VIEW(GHB_WIDGET (ud->builder, "activity_view"));
	gtk_widget_modify_font(GTK_WIDGET(textview), font_desc);      
	pango_font_description_free (font_desc);      

	// Everything should be go-to-go.  Lets rock!

	gtk_main ();
	gtk_status_icon_set_visible(si, FALSE);
	ghb_backend_close();
	if (ud->queue)
		ghb_value_free(ud->queue);
	ghb_value_free(ud->settings);
	g_io_channel_unref(ud->activity_log);
	ghb_settings_close();
#if !defined(_WIN32)
	notify_uninit();
#endif
	g_free(ud);

	return 0;
}
Example #13
0
/*
static void tvsub(struct timeval *tdiff, struct timeval *t1, struct timeval *t0)
{
	tdiff->tv_sec = t1->tv_sec - t0->tv_sec;
	tdiff->tv_usec = t1->tv_usec - t0->tv_usec;
	while (tdiff->tv_usec < 0)
		tdiff->tv_sec--, tdiff->tv_usec += 1000000;
}
static int Nread(GstElement * dccpclientsrc)
{
	sock=socket (AF_INET, SOCK_DCCP, IPPROTO_DCCP);
	g_object_get(G_OBJECT(dccpclientsrc), "sockfd", &sock, NULL);



	struct tfrc_rx_info tfrc;
	socklen_t len = sizeof(tfrc);
	struct timeval now, onow;


	getsockopt(sock, SOL_DCCP, DCCP_SOCKOPT_CCID_RX_INFO,(char*)&tfrc, &len);

	gettimeofday(&now, NULL);
	tvsub(&onow, &now, &time0);
	printf("%ld.%06ld %u %u %u\n",
			onow.tv_sec, onow.tv_usec,
			tfrc.tfrcrx_x_recv,
			tfrc.tfrcrx_rtt,
			tfrc.tfrcrx_p);
	//if (tfrc.tfrcrx_p>0)
		//tfrc.tfrcrx_p=0;
		//setsockopt(sock, SOL_DCCP, DCCP_SOCKOPT_CCID_TX_INFO,&tfrc, sizeof(tfrc));




	return 1;
}
*/
int main (int argc, char *argv[]){

	GMainLoop *loop;
	GstBus *bus;
	GstElement *pipeline, *ffmpegcolorspace, *ximagesink, *h264parse, *ffdec_h264, *dccpclientsrc;


	gchar *host="127.0.0.1";
	gint port = 4000;
	gint ccid = 3;
	GOptionContext *context = NULL;
	GError *err;

	/* Option Entry */

	GOptionEntry entries[] = 
	{
		{"Port", 'p', 0, G_OPTION_ARG_INT, &port, "The port to receive packets from (default: 4000)", NULL},
		{"Host", 'i', 0, G_OPTION_ARG_STRING, &host, "The host IP address to receive packets from (default: localhost)", NULL}, 
		{"ccid", 'c', 0, G_OPTION_ARG_INT, &ccid, "The Congestion Control IDentified to be used (default: 3)", NULL}, 
		{NULL}
	};

	if (!g_thread_supported())
	  g_thread_init (NULL);

	context = g_option_context_new("- TFRC over DCCP");

	g_option_context_add_main_entries(context, entries, NULL);

	g_option_context_add_group(context, gst_init_get_option_group());

	if (!g_option_context_parse(context, &argc, &argv, &err)) {
		g_error("%s\n", err->message);
		return FALSE;
	}

	/* initialize GStreamer */

	gst_init (&argc, &argv);
	loop = g_main_loop_new (NULL, FALSE);



	/* create elements */

	pipeline = gst_pipeline_new ("video-sender");

	ximagesink = gst_element_factory_make ("ximagesink", "ximagesink");

	ffmpegcolorspace = gst_element_factory_make ("ffmpegcolorspace", "ffmpegcolorspace");

	h264parse = gst_element_factory_make ("h264parse", "h264parse");

	ffdec_h264 = gst_element_factory_make ("ffdec_h264", "ffdec_h264");

	dccpclientsrc = gst_element_factory_make ("dccpclientsrc", "client-source");

	if (!pipeline || !ximagesink || !ffmpegcolorspace || !h264parse || !ffdec_h264 || !dccpclientsrc) {
		g_print ("One element could not be created\n");
		return -1;
	}


	
	g_object_set (G_OBJECT (dccpclientsrc), "host", host, NULL);
	g_object_set (G_OBJECT (dccpclientsrc), "port", port, NULL);
	g_object_set (G_OBJECT (dccpclientsrc), "ccid", ccid, NULL);

	bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));

	gst_bus_add_watch (bus, bus_call, loop);

	gst_object_unref (bus);

	/* put all elements in a bin */

	gst_bin_add_many (GST_BIN (pipeline), dccpclientsrc, h264parse, ffdec_h264,ffmpegcolorspace, ximagesink, NULL);

	gst_element_link_many (dccpclientsrc, h264parse, ffdec_h264,ffmpegcolorspace,  ximagesink, NULL);



	/* Now set to playing and iterate. */

	g_print ("Setting to PLAYING\n");
	gst_element_set_state (pipeline, GST_STATE_PLAYING);
	g_print ("Running\n");


  	//g_timeout_add(1000,(GSourceFunc)Nread, dccpclientsrc);
	g_main_loop_run (loop);

	/* clean up nicely */

	g_print ("Returned, stopping playback\n");
	gst_element_set_state (pipeline, GST_STATE_NULL);
	g_print ("Deleting pipeline\n");
	gst_object_unref (GST_OBJECT (pipeline));

	return 0;
}
Example #14
0
int main(void){
	
	GThread *theThread;
	GtkWidget *window;
	GtkWidget *save;
	GtkWidget *hbox;
	GtkWidget *theTable;
	GtkWidget *eBox, *eBox2;
	GtkWidget *lsh,*lsl,*lvh,*lvl;
	
	gtk_init(0,NULL);
	
	loadVars("segVals.dat",theVars);
	//int index=getIndex();
	
	window=gtk_window_new(GTK_WINDOW_TOPLEVEL);
	hbox=gtk_hbox_new(FALSE,2);
	image=gtk_image_new();
	gseg=gtk_image_new();
	eBox=gtk_event_box_new();
	eBox2=gtk_event_box_new();
	theTable=gtk_table_new(5,2,TRUE);
  save = gtk_button_new_with_label("Save!");
	spinvh=gtk_spin_button_new_with_range(0,255,1);
	spinvl=gtk_spin_button_new_with_range(0,255,1);
	spinsh=gtk_spin_button_new_with_range(0,255,1);
	spinsl=gtk_spin_button_new_with_range(0,255,1);
	lsh=gtk_label_new_with_mnemonic("sh");
	lsl=gtk_label_new_with_mnemonic("sl");
	lvh=gtk_label_new_with_mnemonic("vh");
	lvl=gtk_label_new_with_mnemonic("vl");
	hval=gtk_label_new_with_mnemonic("Hue=0");
	
	gtk_window_set_title(GTK_WINDOW(window),"gtk application");
	
	g_signal_connect(window,"delete_event",G_CALLBACK(kill_window),NULL);
	g_signal_connect(eBox,"button_press_event",G_CALLBACK(pressed),image);
	g_signal_connect(eBox2,"button_press_event",G_CALLBACK(pressed),image);
	g_signal_connect(save,"button_press_event",G_CALLBACK(theSaver),NULL);
	g_signal_connect(spinsh,"changed",G_CALLBACK(updateValue), (gpointer)1);
	g_signal_connect(spinsl,"changed",G_CALLBACK(updateValue),(gpointer)2);
	g_signal_connect(spinvh,"changed",G_CALLBACK(updateValue),(gpointer)3);
	g_signal_connect(spinvl,"changed",G_CALLBACK(updateValue),(gpointer)4);//*/
	
	gtk_table_attach_defaults(GTK_TABLE(theTable),spinsh,0,1,0,1);
	gtk_table_attach_defaults(GTK_TABLE(theTable),spinsl,0,1,1,2);
	gtk_table_attach_defaults(GTK_TABLE(theTable),spinvh,0,1,2,3);
	gtk_table_attach_defaults(GTK_TABLE(theTable),spinvl,0,1,3,4);
	gtk_table_attach_defaults(GTK_TABLE(theTable),lsh,1,2,0,1);
	gtk_table_attach_defaults(GTK_TABLE(theTable),lsl,1,2,1,2);
	gtk_table_attach_defaults(GTK_TABLE(theTable),lvh,1,2,2,3);
	gtk_table_attach_defaults(GTK_TABLE(theTable),lvl,1,2,3,4);
	gtk_table_attach_defaults(GTK_TABLE(theTable),hval,0,2,4,5);
	
				updateLimits();
				/*gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinsh),theVars[7+theIndex*2].theInt);
				gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinsl),theVars[6+theIndex*2].theInt);
				gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinvh),theVars[13+theIndex*2].theInt);
				gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinvl),theVars[12+theIndex*2].theInt);//*/
	
	gtk_container_add(GTK_CONTAINER(eBox),image);
	gtk_container_add(GTK_CONTAINER(eBox2),gseg);
	//gtk_box_pack_start(GTK_BOX(hbox),gseg,FALSE,FALSE,2);
	gtk_box_pack_start(GTK_BOX(hbox),eBox2,FALSE,FALSE,2);
	gtk_box_pack_start(GTK_BOX(hbox),eBox,FALSE,FALSE,2);
	gtk_box_pack_start(GTK_BOX(hbox),theTable,FALSE,FALSE,2);
	gtk_box_pack_start(GTK_BOX(hbox),save,TRUE,TRUE,2);
	//gtk_box_pack_start(GTK_BOX(hbox),save,FALSE,FALSE,2);
	gtk_container_add(GTK_CONTAINER(window),hbox);
	
	  if( g_thread_supported() )
  {
     g_thread_init(NULL);
     gdk_threads_init();                   // Called to initialize internal mutex "gdk_threads_mutex".
     printf("g_thread supported\n");
  }
  else
  {
     printf("g_thread NOT supported\n");
     exit(0);
  }
  theThread = g_thread_create((GThreadFunc)ocvThread, NULL, TRUE, NULL);
  assert(theThread!=NULL);
  
	gtk_widget_show_all(window);
	
	gtk_main();
	
	return 0;
}	
/**
 * CGstMediaManager::Init().
 *
 * @param   data    user-defined data. Pointer to this.
 * @return  Java long reference to the media.
 */
uint32_t CGstMediaManager::Init()
{
    GError*     pError = NULL;
    uint32_t    uRetCode = ERROR_NONE;

#if ENABLE_LOWLEVELPERF && TARGET_OS_MAC
    g_mem_set_vtable (glib_mem_profiler_table);
#endif

#if ENABLE_VISUAL_STUDIO_MEMORY_LEAKS_DETECTION && TARGET_OS_WIN32
    _CrtSetDbgFlag ( 0 );
#endif // ENABLE_VISUAL_STUDIO_MEMORY_LEAKS_DETECTION

    //***** Try to initialize the GStreamer system
    if (!g_thread_supported())
        g_thread_init (NULL);

    LOWLEVELPERF_EXECTIMESTART("gst_init_check()");
    // disable installing SIGSEGV signal handling as it interferes with Java's signal handling
    gst_segtrap_set_enabled(false);
    if (!gst_init_check(NULL, NULL, NULL))
    {
        LOGGER_LOGMSG(LOGGER_DEBUG, "Could not init GStreamer!\n");
        return ERROR_MANAGER_ENGINEINIT_FAIL;
    }
    LOWLEVELPERF_EXECTIMESTOP("gst_init_check()");

#if ENABLE_VISUAL_STUDIO_MEMORY_LEAKS_DETECTION && TARGET_OS_WIN32
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif // ENABLE_VISUAL_STUDIO_MEMORY_LEAKS_DETECTION

    //***** Create mutex and condition variable
    m_pRunloopCond = g_cond_new();
    m_pRunloopMutex = g_mutex_new();

#if ENABLE_VISUAL_STUDIO_MEMORY_LEAKS_DETECTION && TARGET_OS_WIN32
    _CrtSetDbgFlag(0);
#endif // ENABLE_VISUAL_STUDIO_MEMORY_LEAKS_DETECTION

    //***** Create the primary run loop
    m_pMainLoopThread = g_thread_create((GThreadFunc)run_loop, this, FALSE, &pError);
    if (m_pMainLoopThread == NULL)
    {
        LOGGER_LOGMSG(LOGGER_DEBUG, "Could not create main GThread!!\n");
        LOGGER_LOGMSG(LOGGER_DEBUG, pError->message);
        return ERROR_MANAGER_RUNLOOP_FAIL;
    }

#if ENABLE_VISUAL_STUDIO_MEMORY_LEAKS_DETECTION && TARGET_OS_WIN32
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif // ENABLE_VISUAL_STUDIO_MEMORY_LEAKS_DETECTION

    //***** Wait till the run loop has fully initialized.  Bad things happen if we do not do this, including crashers.
    g_mutex_lock(m_pRunloopMutex);
    while (NULL == m_pMainLoop)
        g_cond_wait(m_pRunloopCond, m_pRunloopMutex);
    g_mutex_unlock(m_pRunloopMutex);

    if (m_bMainLoopCreateFailed)
        uRetCode = ERROR_GSTREAMER_MAIN_LOOP_CREATE;

    // Free no longer needed GCond.
    if (NULL != m_pRunloopCond)
    {
        g_cond_free(m_pRunloopCond);
        m_pRunloopCond = NULL;
    }

    // Free no longer needed GMutex.
    if (NULL != m_pRunloopMutex)
    {
        g_mutex_free(m_pRunloopMutex);
        m_pRunloopMutex = NULL;
    }

    // Set the default Glib log handler.
    g_log_set_default_handler (GlibLogFunc, this);

    return uRetCode;
}
//static
bool
MediaPluginGStreamer010::startup()
{
	// first - check if GStreamer is explicitly disabled
	if (NULL != getenv("LL_DISABLE_GSTREAMER"))
		return false;

	// only do global GStreamer initialization once.
	if (!mDoneInit)
	{
#if !GLIB_CHECK_VERSION(2, 36, 0)
#if !GLIB_CHECK_VERSION(2, 32, 0)
		if (!g_thread_supported()) g_thread_init(NULL);
#endif
		// Init the glib type system - we need it.
		g_type_init();
#endif
		set_gst_plugin_path();


/*
		// Get symbols!
#if LL_DARWIN
		if (! grab_gst_syms("libgstreamer-0.10.dylib",
				    "libgstvideo-0.10.dylib") )
#elseif LL_WINDOWS
		if (! grab_gst_syms("libgstreamer-0.10.dll",
				    "libgstvideo-0.10.dll") )
#else // linux or other ELFy unixoid
		if (! grab_gst_syms("libgstreamer-0.10.so.0",
				    "libgstvideo-0.10.so.0") )
#endif
		{
			WARNMSG("Couldn't find suitable GStreamer 0.10 support on this system - video playback disabled.");
			return false;
		}
*/
// 		if (gst_segtrap_set_enabled)
// 		{
			gst_segtrap_set_enabled(FALSE);
// 		}
// 		else
// 		{
// 			WARNMSG("gst_segtrap_set_enabled() is not available; plugin crashes won't be caught.");
// 		}
/*
#if LL_LINUX
		// Gstreamer tries a fork during init, waitpid-ing on it,
		// which conflicts with any installed SIGCHLD handler...
		struct sigaction tmpact, oldact;
		if (gst_registry_fork_set_enabled) {
			// if we can disable SIGCHLD-using forking behaviour,
			// do it.
			gst_registry_fork_set_enabled(false);
		}
		else {
			// else temporarily install default SIGCHLD handler
			// while GStreamer initialises
			tmpact.sa_handler = SIG_DFL;
			sigemptyset( &tmpact.sa_mask );
			tmpact.sa_flags = SA_SIGINFO;
			sigaction(SIGCHLD, &tmpact, &oldact);
		}
#endif // LL_LINUX
*/
		// Protect against GStreamer resetting the locale, yuck.
		static std::string saved_locale;
		saved_locale = setlocale(LC_ALL, NULL);

		// finally, try to initialize GStreamer!
		GError *err = NULL;
		gboolean init_gst_success = gst_init_check(NULL, NULL, &err);

		// restore old locale
		setlocale(LC_ALL, saved_locale.c_str() );
/*
#if LL_LINUX
		// restore old SIGCHLD handler
		if (!gst_registry_fork_set_enabled)
			sigaction(SIGCHLD, &oldact, NULL);
#endif // LL_LINUX
*/
		if (!init_gst_success) // fail
		{
			if (err)
			{
				WARNMSG("GST init failed: %s", err->message);
				g_error_free(err);
			}
			else
			{
				WARNMSG("GST init failed for unspecified reason.");
			}
			return false;
		}

		// Set up logging facilities
		gst_debug_remove_log_function( gst_debug_log_default );
//		gst_debug_add_log_function( gstreamer_log, NULL );

		// Init our custom plugins - only really need do this once.
		gst_slvideo_init_class();
/*
		// List the plugins GStreamer can find
		LL_DEBUGS("MediaImpl") << "Found GStreamer plugins:" << LL_ENDL;
		GList *list;
		GstRegistry *registry = gst_registry_get_default();
		std::string loaded = "";
		for (list = gst_registry_get_plugin_list(registry);
		     list != NULL;
		     list = g_list_next(list))
		{	 
			GstPlugin *list_plugin = (GstPlugin *)list->data;
			(bool)gst_plugin_is_loaded(list_plugin) ? loaded = "Yes" : loaded = "No";
			LL_DEBUGS("MediaImpl") << gst_plugin_get_name(list_plugin) << ", loaded? " << loaded << LL_ENDL;
		}
		gst_plugin_list_free(list);
*/
		mDoneInit = true;
	}

	return true;
}
int
main (int argc, char **argv)
{
  GError *err = NULL;
  GstDiscoverer *dc;
  gint timeout = 10;
  GOptionEntry options[] = {
    {"async", 'a', 0, G_OPTION_ARG_NONE, &async,
        "Run asynchronously", NULL},
    {"silent", 's', 0, G_OPTION_ARG_NONE, &silent,
        "Don't output the information structure", NULL},
    {"timeout", 't', 0, G_OPTION_ARG_INT, &timeout,
        "Specify timeout (in seconds, default 10)", "T"},
    /* {"elem", 'e', 0, G_OPTION_ARG_NONE, &elem_seek, */
    /*     "Seek on elements instead of pads", NULL}, */
    {"verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose,
        "Verbose properties", NULL},
    {NULL}
  };
  GOptionContext *ctx;

#if !GLIB_CHECK_VERSION (2, 31, 0)
  if (!g_thread_supported ())
    g_thread_init (NULL);
#endif

  ctx =
      g_option_context_new
      ("- discover files synchronously with GstDiscoverer");
  g_option_context_add_main_entries (ctx, options, NULL);
  g_option_context_add_group (ctx, gst_init_get_option_group ());

  if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
    g_print ("Error initializing: %s\n", err->message);
    exit (1);
  }

  g_option_context_free (ctx);

  if (argc < 2) {
    g_print ("usage: %s <uris>\n", argv[0]);
    exit (-1);
  }

  dc = gst_discoverer_new (timeout * GST_SECOND, &err);
  if (G_UNLIKELY (dc == NULL)) {
    g_print ("Error initializing: %s\n", err->message);
    exit (1);
  }

  if (async == FALSE) {
    gint i;
    for (i = 1; i < argc; i++)
      process_file (dc, argv[i]);
  } else {
    PrivStruct *ps = g_new0 (PrivStruct, 1);
    GMainLoop *ml = g_main_loop_new (NULL, FALSE);

    ps->dc = dc;
    ps->argc = argc;
    ps->argv = argv;

    /* adding uris will be started when the mainloop runs */
    g_idle_add ((GSourceFunc) _run_async, ps);

    /* connect signals */
    g_signal_connect (dc, "discovered", G_CALLBACK (_new_discovered_uri), NULL);
    g_signal_connect (dc, "finished", G_CALLBACK (_discoverer_finished), ml);

    gst_discoverer_start (dc);
    /* run mainloop */
    g_main_loop_run (ml);

    gst_discoverer_stop (dc);
    g_free (ps);
    g_main_loop_unref (ml);
  }
  g_object_unref (dc);

  return 0;
}
Example #18
0
/* Rather than inline this one, we just declare it as a function, to prevent
 * GCC warning about inline failure. */
fluid_cond_t *
new_fluid_cond (void)
{
  if (!g_thread_supported ()) g_thread_init (NULL);
  return g_cond_new ();
}
gint
main (gint argc, gchar **argv)
{
	GtkWidget       *window;
	GOptionContext  *context;
	const gchar     *filename;
	EvDocumentModel *model;
	GError          *error = NULL;

#ifdef G_OS_WIN32
    if (fileno (stdout) != -1 &&
 	  _get_osfhandle (fileno (stdout)) != -1)
	{
	  /* stdout is fine, presumably redirected to a file or pipe */
	}
    else
    {
	  typedef BOOL (* WINAPI AttachConsole_t) (DWORD);

	  AttachConsole_t p_AttachConsole =
	    (AttachConsole_t) GetProcAddress (GetModuleHandle ("kernel32.dll"), "AttachConsole");

	  if (p_AttachConsole != NULL && p_AttachConsole (ATTACH_PARENT_PROCESS))
      {
	      freopen ("CONOUT$", "w", stdout);
	      dup2 (fileno (stdout), 1);
	      freopen ("CONOUT$", "w", stderr);
	      dup2 (fileno (stderr), 2);

      }
	}
#endif

	/* Init glib threads asap */
	if (!g_thread_supported ())
		g_thread_init (NULL);

#ifdef ENABLE_NLS
	/* Initialize the i18n stuff */
	bindtextdomain (GETTEXT_PACKAGE, ev_get_locale_dir());
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);
#endif
	
	context = g_option_context_new (_("MATE Document Previewer"));
	g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
	g_option_context_add_main_entries (context, goption_options, GETTEXT_PACKAGE);

	g_option_context_add_group (context, gtk_get_option_group (TRUE));
	
	if (!g_option_context_parse (context, &argc, &argv, &error)) {
		g_warning ("Error parsing command line arguments: %s", error->message);
		g_error_free (error);
		g_option_context_free (context);

		return 1;
	}
	g_option_context_free (context);

	if (!filenames) {
		g_warning ("File argument is required");
		
		return 1;
	}

	filename = filenames[0];
	
	if (!g_file_test (filename, G_FILE_TEST_IS_REGULAR)) {
		g_warning ("Filename \"%s\" does not exist or is not a regular file", filename);

		return 1;
	}

	if (!ev_init ())
		return 1;

	ev_stock_icons_init ();

	g_set_application_name (_("MATE Document Previewer"));
	gtk_window_set_default_icon_name ("atril");

	model = ev_document_model_new ();
	window = ev_previewer_window_new (model);
	ev_previewer_window_set_source_file (EV_PREVIEWER_WINDOW (window), filename);
	ev_previewer_window_set_print_settings (EV_PREVIEWER_WINDOW (window), print_settings);
	g_signal_connect (window, "delete-event",
			  G_CALLBACK (gtk_main_quit), NULL);
	g_signal_connect (window, "destroy",
			  G_CALLBACK (gtk_main_quit), NULL);
	gtk_widget_show (window);

	ev_previewer_load_document (filename, model);
	
	gtk_main ();

	if (unlink_temp_file)
		ev_previewer_unlink_tempfile (filename);
	if (print_settings)
		ev_previewer_unlink_tempfile (print_settings);

	ev_shutdown ();
	ev_stock_icons_shutdown ();
	g_object_unref (model);
	
	return 0;
}
Example #20
0
/* This function recieves the START_TAPER command from driver, and
   returns the attached timestamp. */
static gboolean find_first_tape(taper_state_t * state) {
    struct cmdargs *cmdargs;
    tape_search_request_t search_request;
    GThread * tape_search = NULL;
    gboolean use_threads;

    /* We save the value here in case it changes while we're running. */
    use_threads = g_thread_supported();

    search_request.state = state;
    search_request.prolong = TRUE;
    search_request.errmsg = NULL;
    
    if (use_threads) {
        tape_search = g_thread_create(tape_search_thread,
                                      &search_request, TRUE, NULL);
    }

    cmdargs = getcmd();

    switch (cmdargs->cmd) {
    case START_TAPER: {
        gboolean search_result;
        state->driver_start_time = strdup(cmdargs->argv[1]);
        if (use_threads) {
            search_result = GPOINTER_TO_INT(g_thread_join(tape_search));
        } else {
            search_result =
                GPOINTER_TO_INT(tape_search_thread(&search_request));
        }
        if (search_result) {
            putresult(TAPER_OK, "\n");
        } else {
	    char *msg = quote_string(_("Could not find a tape to use"));
            putresult(TAPE_ERROR, "99-99999 %s\n", msg);
	    log_add(L_ERROR, "no-tape [%s]", "Could not find a tape to use");
	    if (search_request.errmsg != NULL) {
		char *c, *c1;
		c = c1 = search_request.errmsg;
		while (*c != '\0') {
		    if (*c == '\n') {
			*c = '\0';
			log_add(L_WARNING,"%s", c1);
			c1 = c+1;
		    }
		    c++;
		}
		if (strlen(c1) > 1 )
		    log_add(L_WARNING,"%s", c1);
	    }
        }
	amfree(search_request.errmsg);
	free_cmdargs(cmdargs);
        return TRUE;
    }
    case QUIT:
        search_request.prolong = FALSE;
        if (use_threads) {
            g_thread_join(tape_search);
        }
	free_cmdargs(cmdargs);
        return send_quitting(state);
    default:
        error("error [file_reader_side cmd %d argc %d]", cmdargs->cmd, cmdargs->argc);
    }

    g_assert_not_reached();
}
Example #21
0
// use unusual names for the parameters to avoid conflict with wxApp::arg[cv]
bool wxApp::Initialize(int& argc_, wxChar **argv_)
{
    if ( !wxAppBase::Initialize(argc_, argv_) )
        return false;

#if wxUSE_THREADS
    if (!g_thread_supported())
    {
        g_thread_init(NULL);
        gdk_threads_init();
    }
#endif // wxUSE_THREADS

    // gtk+ 2.0 supports Unicode through UTF-8 strings
    wxConvCurrent = &wxConvUTF8;

    // decide which conversion to use for the file names

    // (1) this variable exists for the sole purpose of specifying the encoding
    //     of the filenames for GTK+ programs, so use it if it is set
    wxString encName(wxGetenv(wxT("G_FILENAME_ENCODING")));
    encName = encName.BeforeFirst(wxT(','));
    if (encName.CmpNoCase(wxT("@locale")) == 0)
        encName.clear();
    encName.MakeUpper();
#if wxUSE_INTL
    if (encName.empty())
    {
        // (2) if a non default locale is set, assume that the user wants his
        //     filenames in this locale too
        encName = wxLocale::GetSystemEncodingName().Upper();
        // (3) finally use UTF-8 by default
        if (encName.empty() || encName == wxT("US-ASCII"))
            encName = wxT("UTF-8");
        wxSetEnv(wxT("G_FILENAME_ENCODING"), encName);
    }
#else
    if (encName.empty())
        encName = wxT("UTF-8");

    // if wxUSE_INTL==0 it probably indicates that only "C" locale is supported
    // by the program anyhow so prevent GTK+ from calling setlocale(LC_ALL, "")
    // from gtk_init_check() as it does by default
    gtk_disable_setlocale();

#endif // wxUSE_INTL
    static wxConvBrokenFileNames fileconv(encName);
    wxConvFileName = &fileconv;


    bool init_result;
    int i;

#if wxUSE_UNICODE
    // gtk_init() wants UTF-8, not wchar_t, so convert
    char **argvGTK = new char *[argc_ + 1];
    for ( i = 0; i < argc_; i++ )
    {
        argvGTK[i] = wxStrdupA(wxConvUTF8.cWX2MB(argv_[i]));
    }

    argvGTK[argc_] = NULL;

    int argcGTK = argc_;

#ifdef __WXGPE__
    init_result = true;  // is there a _check() version of this?
    gpe_application_init( &argcGTK, &argvGTK );
#else
    init_result = gtk_init_check( &argcGTK, &argvGTK );
#endif
    wxUpdateLocaleIsUtf8();

    if ( argcGTK != argc_ )
    {
        // we have to drop the parameters which were consumed by GTK+
        for ( i = 0; i < argcGTK; i++ )
        {
            while ( strcmp(wxConvUTF8.cWX2MB(argv_[i]), argvGTK[i]) != 0 )
            {
                memmove(argv_ + i, argv_ + i + 1, (argc_ - i)*sizeof(*argv_));
            }
        }

        argc_ = argcGTK;
        argv_[argc_] = NULL;
    }
    //else: gtk_init() didn't modify our parameters

    // free our copy
    for ( i = 0; i < argcGTK; i++ )
    {
        free(argvGTK[i]);
    }

    delete [] argvGTK;
#else // !wxUSE_UNICODE
    // gtk_init() shouldn't actually change argv_ itself (just its contents) so
    // it's ok to pass pointer to it
    init_result = gtk_init_check( &argc_, &argv_ );
#endif // wxUSE_UNICODE/!wxUSE_UNICODE

    // update internal arg[cv] as GTK+ may have removed processed options:
    this->argc = argc_;
    this->argv = argv_;

    if ( m_traits )
    {
        // if there are still GTK+ standard options unparsed in the command
        // line, it means that they were not syntactically correct and GTK+
        // already printed a warning on the command line and we should now
        // exit:
        wxArrayString opt, desc;
        m_traits->GetStandardCmdLineOptions(opt, desc);

        for ( i = 0; i < argc_; i++ )
        {
            // leave just the names of the options with values
            const wxString str = wxString(argv_[i]).BeforeFirst('=');

            for ( size_t j = 0; j < opt.size(); j++ )
            {
                // remove the leading spaces from the option string as it does
                // have them
                if ( opt[j].Trim(false).BeforeFirst('=') == str )
                {
                    // a GTK+ option can be left on the command line only if
                    // there was an error in (or before, in another standard
                    // options) it, so abort, just as we do if incorrect
                    // program option is given
                    wxLogError(_("Invalid GTK+ command line option, use \"%s --help\""),
                               argv_[0]);
                    return false;
                }
            }
        }
    }

    if ( !init_result )
    {
        wxLogError(_("Unable to initialize GTK+, is DISPLAY set properly?"));
        return false;
    }

    // we can not enter threads before gtk_init is done
    gdk_threads_enter();

#if wxUSE_INTL
    wxFont::SetDefaultEncoding(wxLocale::GetSystemEncoding());
#endif

    // make sure GtkWidget type is loaded, idle hooks need it
    g_type_class_ref(GTK_TYPE_WIDGET);
    WakeUpIdle();

    return true;
}
Example #22
0
/* If handle is NULL, then this function assumes that we are in startup mode.
 * In that case it will wait for a command from driver. If handle is not NULL,
 * this this function will ask for permission with REQUEST-NEW-TAPE. */
static gboolean find_new_tape(taper_state_t * state, dump_info_t * dump) {
    GThread * tape_search = NULL;
    tape_search_request_t search_request;
    gboolean use_threads;
    struct cmdargs *cmdargs;
    cmd_t cmd;

    if (state->device != NULL) {
        return TRUE;
    }

    /* We save the value here in case it changes while we're running. */
    use_threads = g_thread_supported();

    search_request.state = state;
    search_request.prolong = TRUE;
    search_request.errmsg = NULL;
    if (use_threads) {
        tape_search = g_thread_create(tape_search_thread,
                                      &search_request, TRUE, NULL);
    }
    
    putresult(REQUEST_NEW_TAPE, "%s\n", dump->handle);
    cmdargs = getcmd();
    cmd = cmdargs->cmd;

    switch (cmd) {
    default:
        g_fprintf(stderr, "taper: Got odd message from driver, expected NEW-TAPE or NO-NEW-TAPE.\n");
        /* FALLTHROUGH. */
    case NEW_TAPE: {
        gboolean search_result;
        if (use_threads) {
            search_result = GPOINTER_TO_INT(g_thread_join(tape_search));
        } else {
            search_result =
                GPOINTER_TO_INT(tape_search_thread(&search_request));
        }
        if (search_result) {
            /* We don't say NEW_TAPE until we actually write the label. */
	    amfree(search_request.errmsg);
	    free_cmdargs(cmdargs);
            return TRUE;
        } else {
            putresult(NO_NEW_TAPE, "%s\n", dump->handle);
            log_taper_scan_errmsg(search_request.errmsg);
	    log_add(L_ERROR, "no-tape [%s]", "No more writable valid tape found");
	    free_cmdargs(cmdargs);
            return FALSE;
        }
    }
    case NO_NEW_TAPE:
        search_request.prolong = FALSE;
        if (use_threads) {
            g_thread_join(tape_search);
        }
	log_add(L_ERROR, "no-tape [%s]", cmdargs->argv[1]);
	state->last_errmsg = stralloc(cmdargs->argv[1]);
	free_cmdargs(cmdargs);
        return FALSE;
    }
    /* NOTREACHED */
}
Example #23
0
File: wrapper.c Project: WDavidX/OS
/**********
 * Name:	create_browser
 * Input:	'type' - either controller or url rendering tab
 *		'tab_index' - which index
 *		'create_new_tab_cb' - the call back function to create a new tab
 * 		'uri_entered_cb' - the call back function to help make a persistent window when you hit enter
 * 		'b_window' - double pointer to a browser_window type to get initialized
 * 		'comm_channel' - the channel of a particular tab to chatter on; full of FD's.
 * Output:      error description
 * Function:    Sets up the location of the browser window, 
 * 		allocates space for data etc., (building it if it's a CONTROLLER_TAB 
 * 		or making it the empty boring window for tabs), labels window pieces, 
 * 		and shows the end window result.
 */
int create_browser(tab_type t_type, 
		   int tab_index,
		   void (*create_new_tab_cb)(void), 
		   void (*uri_entered_cb)(void), 
		   browser_window **b_window,
		   comm_channel comm_channel)
{
  GtkWidget *window;
  GtkWidget *table;

  gtk_init(NULL, NULL);
  if (!g_thread_supported ())
    g_thread_init (NULL);

  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

  gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER_ALWAYS);

  if(t_type == CONTROLLER_TAB)
    table = gtk_table_new(2,4,FALSE);
  else 
    table = gtk_table_new(2,1,FALSE);

  gtk_container_add (GTK_CONTAINER (window), table);

  gtk_table_set_row_spacing(GTK_TABLE(table), 0, 20);

  // Allocate space for browser-window to be passed to various callbacks.
  *b_window = calloc(1, sizeof(browser_window));
  (*b_window)->web_view = NULL;
  (*b_window)->notebook = gtk_notebook_new ();
  (*b_window)->tab_index = tab_index;
  sprintf((*b_window)->tab_label, "Tab %d", tab_index);
  memcpy((*b_window)->channel.parent_to_child_fd, 
	  comm_channel.parent_to_child_fd, 
	  2*sizeof(int));
  memcpy((*b_window)->channel.child_to_parent_fd,
  	  comm_channel.child_to_parent_fd,
	  2*sizeof(int));


  gtk_notebook_set_tab_pos (GTK_NOTEBOOK ((*b_window)->notebook), GTK_POS_TOP);
  gtk_table_attach_defaults (GTK_TABLE (table), (*b_window)->notebook, 0, 6, 1, 2);
  gtk_widget_show ((*b_window)->notebook);
 
  if(t_type == CONTROLLER_TAB) 
  {
    gtk_window_set_title(GTK_WINDOW(window), "CONTROLLER-TAB");
    
    GtkWidget* url_label = gtk_label_new("URL");
    gtk_table_attach_defaults(GTK_TABLE(table), url_label, 0,1,0,1);
    gtk_widget_show(url_label);

    GtkWidget* uri_entry = gtk_entry_new();
    gtk_table_attach_defaults(GTK_TABLE(table), uri_entry, 1, 2, 0, 1); 
    gtk_widget_show(uri_entry);
    g_signal_connect (G_OBJECT (uri_entry), "activate", uri_entered_cb, *b_window);
    (*b_window)->uri_entry = uri_entry;

    GtkWidget* tab_label = gtk_label_new("Tab Number");
    gtk_table_attach_defaults(GTK_TABLE(table), tab_label, 2,3,0,1);
    gtk_widget_show(tab_label);
  
    GtkWidget* tab_selector = gtk_entry_new();
    gtk_table_attach_defaults(GTK_TABLE(table), tab_selector, 3, 4, 0, 1);
    gtk_widget_show(tab_selector);
    //g_signal_connect (G_OBJECT (uri_entry), "activate", uri_entered_cb, *b_window);
    (*b_window)->tab_selector = tab_selector;
  }
  else
  {
    gtk_window_set_title(GTK_WINDOW(window),"URL-RENDERING TAB");
    (*b_window)->tab_selector = NULL;
    (*b_window)->uri_entry = NULL;
  }

  if(t_type == CONTROLLER_TAB)
  {
    // Create "+" and "-" buttons (for adding and deleting new tabs) 
    // in CONTROLLER tab
    create_add_remove_tab_button("+", G_CALLBACK(create_new_tab_cb), *b_window);
    //create_add_remove_tab_button("-", G_CALLBACK(delete_tab_clicked_cb), *b_window);
  }
  else
  {
     // Create rendering window for ORDINARY tab
     create_labeled_tab(*b_window);
  }
    g_signal_connect(G_OBJECT (window), "destroy", 
		   G_CALLBACK(delete_window_cb), *b_window);
  gtk_widget_show(table);
  gtk_widget_show_all(window);
  return 0;
}
int
main (int argc, char *argv[])
{
  gchar *target_times = NULL;
  gchar *ev_option = NULL;
  gchar *fn_option = NULL;

  GOptionEntry options[] = {
    {"ev-compensation", '\0', 0, G_OPTION_ARG_STRING, &ev_option,
        "EV compensation for source element GstPhotography interface", NULL},
    {"aperture", '\0', 0, G_OPTION_ARG_INT, &aperture,
          "Aperture (size of lens opening) for source element GstPhotography interface",
        NULL},
    {"flash-mode", '\0', 0, G_OPTION_ARG_INT,
          &flash_mode,
        "Flash mode for source element GstPhotography interface", NULL},
    {"scene-mode", '\0', 0, G_OPTION_ARG_INT,
          &scene_mode,
        "Scene mode for source element GstPhotography interface", NULL},
    {"exposure", '\0', 0, G_OPTION_ARG_INT64,
          &exposure,
          "Exposure time (in ms) for source element GstPhotography interface",
        NULL},
    {"iso-speed", '\0', 0, G_OPTION_ARG_INT,
          &iso_speed,
        "ISO speed for source element GstPhotography interface", NULL},
    {"white-balance-mode", '\0', 0, G_OPTION_ARG_INT,
          &wb_mode,
        "White balance mode for source element GstPhotography interface", NULL},
    {"colour-tone-mode", '\0', 0, G_OPTION_ARG_INT,
          &color_mode,
        "Colour tone mode for source element GstPhotography interface", NULL},
    {"directory", '\0', 0, G_OPTION_ARG_STRING, &fn_option,
        "Directory for capture file(s) (default is current directory)", NULL},
    {"mode", '\0', 0, G_OPTION_ARG_INT, &mode,
        "Capture mode (default = 1 (image), 2 = video)", NULL},
    {"capture-time", '\0', 0, G_OPTION_ARG_INT,
          &capture_time,
        "Time to capture video in seconds (default = 10)", NULL},
    {"capture-total", '\0', 0, G_OPTION_ARG_INT, &capture_total,
        "Total number of captures to be done (default = 1)", NULL},
    {"zoom", '\0', 0, G_OPTION_ARG_INT, &zoom,
        "Zoom (100 = 1x (default), 200 = 2x etc.)", NULL},
    {"wrapper-source", '\0', 0, G_OPTION_ARG_STRING, &wrappersrc_name,
          "Camera source wrapper used for setting the video source (default is wrappercamerabinsrc)",
        NULL},
    {"video-source", '\0', 0, G_OPTION_ARG_STRING, &videosrc_name,
        "Video source used in still capture and video recording", NULL},
    {"video-device", '\0', 0, G_OPTION_ARG_STRING, &videodevice_name,
        "Video device to be set on the video source", NULL},
    {"audio-source", '\0', 0, G_OPTION_ARG_STRING, &audiosrc_name,
        "Audio source used in video recording", NULL},
    {"image-pp", '\0', 0, G_OPTION_ARG_STRING, &imagepp_name,
        "List of image post-processing elements separated with comma", NULL},
    {"viewfinder-sink", '\0', 0, G_OPTION_ARG_STRING, &vfsink_name,
        "Viewfinder sink (default = fakesink)", NULL},
    {"image-width", '\0', 0, G_OPTION_ARG_INT, &image_width,
        "Width for image capture", NULL},
    {"image-height", '\0', 0, G_OPTION_ARG_INT, &image_height,
        "Height for image capture", NULL},
    {"view-framerate-num", '\0', 0, G_OPTION_ARG_INT, &view_framerate_num,
        "Framerate numerator for viewfinder", NULL},
    {"view-framerate-den", '\0', 0, G_OPTION_ARG_INT, &view_framerate_den,
        "Framerate denominator for viewfinder", NULL},
    {"preview-caps", '\0', 0, G_OPTION_ARG_STRING, &preview_caps_name,
        "Preview caps (e.g. video/x-raw-rgb,width=320,height=240)", NULL},
    {"viewfinder-filter", '\0', 0, G_OPTION_ARG_STRING, &viewfinder_filter,
        "Filter to process all frames going to viewfinder sink", NULL},
    {"x-width", '\0', 0, G_OPTION_ARG_INT, &x_width,
        "X window width (default = 320)", NULL},
    {"x-height", '\0', 0, G_OPTION_ARG_INT, &x_height,
        "X window height (default = 240)", NULL},
    {"no-xwindow", '\0', 0, G_OPTION_ARG_NONE, &no_xwindow,
        "Do not create XWindow", NULL},
    {"encoding-target", '\0', 0, G_OPTION_ARG_STRING, &gep_targetname,
        "Video encoding target name", NULL},
    {"encoding-profile", '\0', 0, G_OPTION_ARG_STRING, &gep_profilename,
        "Video encoding profile name", NULL},
    {"encoding-profile-filename", '\0', 0, G_OPTION_ARG_STRING, &gep_filename,
        "Video encoding profile filename", NULL},
    {"image-capture-caps", '\0', 0,
          G_OPTION_ARG_STRING, &image_capture_caps_str,
        "Image capture caps (e.g. video/x-raw-rgb,width=640,height=480)", NULL},
    {"viewfinder-caps", '\0', 0, G_OPTION_ARG_STRING,
          &viewfinder_caps_str,
        "Viewfinder caps (e.g. video/x-raw-rgb,width=640,height=480)", NULL},
    {"video-capture-caps", '\0', 0,
          G_OPTION_ARG_STRING, &video_capture_caps_str,
        "Video capture caps (e.g. video/x-raw-rgb,width=640,height=480)", NULL},
    {NULL}
  };

  GOptionContext *ctx;
  GError *err = NULL;

  if (!g_thread_supported ())
    g_thread_init (NULL);

  ctx = g_option_context_new ("\n\ncamerabin command line test application.");
  g_option_context_add_main_entries (ctx, options, NULL);
  g_option_context_add_group (ctx, gst_init_get_option_group ());
  if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
    g_print ("Error initializing: %s\n", err->message);
    exit (1);
  }
  g_option_context_free (ctx);

  GST_DEBUG_CATEGORY_INIT (camerabin_test, "camerabin-test", 0,
      "camerabin test");

  /* if we fail to create xwindow should we care? */
  if (!no_xwindow)
    create_host_window ();

  /* FIXME: error handling */
  if (ev_option != NULL)
    ev_compensation = strtod (ev_option, (char **) NULL);

  if (vfsink_name == NULL)
    vfsink_name = g_strdup ("fakesink");

  filename = g_string_new (fn_option);
  if (filename->len == 0)
    filename = g_string_append (filename, ".");

  timer = g_timer_new ();

  /* init */
  if (setup_pipeline ()) {
    loop = g_main_loop_new (NULL, FALSE);
    g_idle_add ((GSourceFunc) run_pipeline, NULL);
    g_main_loop_run (loop);
    cleanup_pipeline ();
    g_main_loop_unref (loop);
  }
  /* free */
  g_string_free (filename, TRUE);
  g_free (ev_option);
  g_free (wrappersrc_name);
  g_free (videosrc_name);
  g_free (videodevice_name);
  g_free (audiosrc_name);
  g_free (imagepp_name);
  g_free (vfsink_name);
  g_free (target_times);
  g_free (gep_targetname);
  g_free (gep_profilename);
  g_free (gep_filename);
  g_timer_destroy (timer);

  if (window)
    XDestroyWindow (display, window);

  if (display)
    XCloseDisplay (display);

  return 0;
}
Example #25
0
int
main (int argc, char **argv)
{
  GPtrArray *files;
  gchar **args = NULL;
  guint num, i;
  GError *err = NULL;
  GOptionContext *ctx;
  GOptionEntry options[] = {
    {G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &args, NULL},
    {NULL}
  };
  GTimer *timer;

  if (!g_thread_supported ())
    g_thread_init (NULL);

  ctx = g_option_context_new ("FILES OR DIRECTORIES WITH AUDIO FILES");
  g_option_context_add_main_entries (ctx, options, NULL);
  g_option_context_add_group (ctx, gst_init_get_option_group ());
  if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
    g_print ("Error initializing: %s\n", GST_STR_NULL (err->message));
    exit (1);
  }
  g_option_context_free (ctx);

  if (args == NULL || *args == NULL) {
    g_print ("Please provide one or more directories with audio files\n\n");
    return 1;
  }

  files = g_ptr_array_new ();

  num = g_strv_length (args);
  for (i = 0; i < num; ++i) {
    if (g_path_is_absolute (args[i])) {
      check_arg (files, args[i]);
    } else {
      g_warning ("Argument '%s' is not an absolute file path", args[i]);
    }
  }

  if (files->len == 0) {
    g_print ("Did not find any files\n\n");
    return 1;
  }

  timer = g_timer_new ();

  while (g_timer_elapsed (timer, NULL) < TEST_RUNTIME) {
    gint32 idx;

    idx = g_random_int_range (0, files->len);
    play_file ((const gchar *) g_ptr_array_index (files, idx));
  }

  g_strfreev (args);
  g_timer_destroy (timer);

  return 0;
}
Example #26
0
int main(int argc, char *argv[])
{
	GOptionContext *context;
	GError *error = NULL;
	DBusConnection *conn;
	DBusError err;
	guint signal;

#ifdef NEED_THREADS
	if (g_thread_supported() == FALSE)
		g_thread_init(NULL);
#endif

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

	if (g_option_context_parse(context, &argc, &argv, &error) == FALSE) {
		if (error != NULL) {
			g_printerr("%s\n", error->message);
			g_error_free(error);
		} else
			g_printerr("An unknown error occurred\n");
		exit(1);
	}

	g_option_context_free(context);

	if (option_version == TRUE) {
		printf("%s\n", VERSION);
		exit(0);
	}

	if (option_detach == TRUE) {
		if (daemon(0, 0)) {
			perror("Can't start daemon");
			exit(1);
		}
	}

	if (mkdir(STATEDIR, S_IRUSR | S_IWUSR | S_IXUSR |
				S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) < 0) {
		if (errno != EEXIST)
			perror("Failed to create state directory");
	}

	if (mkdir(STORAGEDIR, S_IRUSR | S_IWUSR | S_IXUSR |
				S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) < 0) {
		if (errno != EEXIST)
			perror("Failed to create storage directory");
	}

	umask(0077);

	main_loop = g_main_loop_new(NULL, FALSE);

#ifdef NEED_THREADS
	if (dbus_threads_init_default() == FALSE) {
		fprintf(stderr, "Can't init usage of threads\n");
		exit(1);
	}
#endif

	signal = setup_signalfd();

	dbus_error_init(&err);

	conn = g_dbus_setup_bus(DBUS_BUS_SYSTEM, CONNMAN_SERVICE, &err);
	if (conn == NULL) {
		if (dbus_error_is_set(&err) == TRUE) {
			fprintf(stderr, "%s\n", err.message);
			dbus_error_free(&err);
		} else
			fprintf(stderr, "Can't register with system bus\n");
		exit(1);
	}

	g_dbus_set_disconnect_function(conn, disconnect_callback, NULL, NULL);

	__connman_log_init(argv[0], option_debug, option_detach,
			option_backtrace, "Connection Manager", VERSION);

	__connman_dbus_init(conn);

	if (option_config == NULL)
		config_init(CONFIGMAINFILE);
	else
		config_init(option_config);

	__connman_inotify_init();
	__connman_technology_init();
	__connman_notifier_init();
	__connman_agent_init();
	__connman_service_init();
	__connman_provider_init();
	__connman_network_init();
	__connman_device_init(option_device, option_nodevice);

	__connman_ippool_init();
	__connman_iptables_init();
	__connman_firewall_init();
	__connman_nat_init();
	__connman_tethering_init();
	__connman_counter_init();
	__connman_manager_init();
	__connman_config_init();
	__connman_stats_init();
	__connman_clock_init();

	__connman_resolver_init(option_dnsproxy);
	__connman_ipconfig_init();
	__connman_rtnl_init();
	__connman_task_init();
	__connman_proxy_init();
	__connman_detect_init();
	__connman_session_init();
	__connman_timeserver_init();
	__connman_connection_init();

	__connman_plugin_init(option_plugin, option_noplugin);

	__connman_rtnl_start();
	__connman_dhcp_init();
	__connman_dhcpv6_init();
	__connman_wpad_init();
	__connman_wispr_init();
	__connman_rfkill_init();

	g_free(option_config);
	g_free(option_device);
	g_free(option_plugin);
	g_free(option_nodevice);
	g_free(option_noplugin);

#ifdef SYSTEMD
	/* Tell systemd that we have started up */
	if( option_systemd )
		sd_notify(0, "READY=1");
#endif

	g_main_loop_run(main_loop);

	g_source_remove(signal);

	__connman_rfkill_cleanup();
	__connman_wispr_cleanup();
	__connman_wpad_cleanup();
	__connman_dhcpv6_cleanup();
	__connman_dhcp_cleanup();
	__connman_session_cleanup();
	__connman_plugin_cleanup();
	__connman_provider_cleanup();
	__connman_connection_cleanup();
	__connman_timeserver_cleanup();
	__connman_detect_cleanup();
	__connman_proxy_cleanup();
	__connman_task_cleanup();
	__connman_rtnl_cleanup();
	__connman_resolver_cleanup();

	__connman_clock_cleanup();
	__connman_stats_cleanup();
	__connman_config_cleanup();
	__connman_manager_cleanup();
	__connman_counter_cleanup();
	__connman_tethering_cleanup();
	__connman_nat_cleanup();
	__connman_firewall_cleanup();
	__connman_iptables_cleanup();
	__connman_ippool_cleanup();
	__connman_device_cleanup();
	__connman_network_cleanup();
	__connman_service_cleanup();
	__connman_agent_cleanup();
	__connman_ipconfig_cleanup();
	__connman_notifier_cleanup();
	__connman_technology_cleanup();
	__connman_inotify_cleanup();

	__connman_dbus_cleanup();

	__connman_log_cleanup(option_backtrace);

	dbus_connection_unref(conn);

	g_main_loop_unref(main_loop);

	if (connman_settings.pref_timeservers != NULL)
		g_strfreev(connman_settings.pref_timeservers);

	g_free(connman_settings.auto_connect);
	g_free(connman_settings.preferred_techs);
	g_strfreev(connman_settings.fallback_nameservers);
	g_strfreev(connman_settings.blacklisted_interfaces);
	g_strfreev(connman_settings.tethering_technologies);

	g_free(option_debug);

	return 0;
}
Example #27
0
int AP_UnixApp::main(const char * szAppName, int argc, char ** argv)
{
    // This is a static function.	
	
	if (!g_thread_supported ())
		g_thread_init (NULL);	
    
    // initialize our application.
	int exit_status = 0;
	AP_UnixApp * pMyUnixApp = new AP_UnixApp(szAppName);

#ifdef WITH_CHAMPLAIN
    gtk_clutter_init (&argc, &argv);
#endif
    
	/* this brace is here to ensure that our local variables on the stack
	 * do not outlive the application object by giving them a lower scope
	 */
	{
		XAP_Args XArgs = XAP_Args(argc, argv);
		AP_Args Args = AP_Args(&XArgs, szAppName, pMyUnixApp);
#ifdef LOGFILE
		UT_String sLogFile = pMyUnixApp->getUserPrivateDirectory();
		sLogFile += "abiLogFile";
		logfile = fopen(sLogFile.c_str(),"a+");
		fprintf(logfile,"About to do gtk_set_locale \n");
		fprintf(logfile,"New logfile \n");
#endif
		// Step 1: Initialize GTK and create the APP.
		// hack needed to intialize gtk before ::initialize
		setlocale(LC_ALL, "");
		gboolean have_display = gtk_init_check(&argc, &argv);
#ifdef LOGFILE
		fprintf(logfile,"Got display %d \n",have_display);
		fprintf(logfile,"Really display %d \n",have_display);
#endif
		if (have_display > 0) {
			Args.addOptions(gtk_get_option_group(TRUE));
			Args.parseOptions();
		}
		else {
			// no display, but we still need to at least parse our own arguments, damnit, for --to, --to-png, and --print
			Args.addOptions(gtk_get_option_group(FALSE));
			Args.parseOptions();
		}

		// if the initialize fails, we don't have icons, fonts, etc.
		if (!pMyUnixApp->initialize(have_display))
		{
			delete pMyUnixApp;
			return -1;	// make this something standard?
		}
	
		// Setup signal handlers, primarily for segfault
		// If we segfaulted before here, we *really* blew it
		struct sigaction sa;
		sa.sa_handler = signalWrapper;
    
		sigfillset(&sa.sa_mask);  // We don't want to hear about other signals
		sigdelset(&sa.sa_mask, SIGABRT); // But we will call abort(), so we can't ignore that
#if defined (SA_NODEFER) && defined (SA_RESETHAND)
		sa.sa_flags = SA_NODEFER | SA_RESETHAND; // Don't handle nested signals
#else
		sa.sa_flags = 0;
#endif
    
		sigaction(SIGSEGV, &sa, NULL);
		sigaction(SIGBUS, &sa, NULL);
		sigaction(SIGILL, &sa, NULL);
		sigaction(SIGQUIT, &sa, NULL);
		sigaction(SIGFPE, &sa, NULL);

		// TODO: handle SIGABRT
	
		// Step 2: Handle all non-window args.
    
		bool windowlessArgsWereSuccessful = true;
		if (!Args.doWindowlessArgs(windowlessArgsWereSuccessful )) {
			delete pMyUnixApp;
			return (windowlessArgsWereSuccessful ? 0 : -1);
		}

		if (have_display) {

			// Step 3: Create windows as appropriate.
			// if some args are botched, it returns false and we should
			// continue out the door.
			// We used to check for bShowApp here.  It shouldn't be needed
			// anymore, because doWindowlessArgs was supposed to bail already. -PL

			if (pMyUnixApp->openCmdLineFiles(&Args))
			{
#if defined(EMBEDDED_TARGET) && EMBEDDED_TARGET == EMBEDDED_TARGET_HILDON
				s_bInitDone = true;
				pMyUnixApp->processStartupQueue();
#endif
				// turn over control to gtk
				gtk_main();
			}
			else
			{
				UT_DEBUGMSG(("DOM: not parsing command line or showing app\n"));
			}
		}
		else {
			fprintf(stderr, "No DISPLAY: this may not be what you want.\n");
			exit_status = 1;
		}
		// unload all loaded plugins (remove some of the memory leaks shown at shutdown :-)
		XAP_ModuleManager::instance().unloadAllPlugins();

		// Step 4: Destroy the App.  It should take care of deleting all frames.
		pMyUnixApp->shutdown();
	}
	
	delete pMyUnixApp;
	
	return exit_status;
}
Example #28
0
File: uzbl.c Project: dusanx/uzbl
int
main (int argc, char* argv[]) {
    gtk_init (&argc, &argv);
    if (!g_thread_supported ())
        g_thread_init (NULL);

    printf("Uzbl start location: %s\n", argv[0]);
    strcpy(executable_path,argv[0]);

    strcat ((char *) XDG_CONFIG_HOME_default, getenv ("HOME"));
    strcat ((char *) XDG_CONFIG_HOME_default, "/.config");

    GError *error = NULL;
    GOptionContext* context = g_option_context_new ("- some stuff here maybe someday");
    g_option_context_add_main_entries (context, entries, NULL);
    g_option_context_add_group (context, gtk_get_option_group (TRUE));
    g_option_context_parse (context, &argc, &argv, &error);
    /* initialize hash table */
    bindings = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, free_action);
	
	soup_session = webkit_get_default_session();
    keycmd = g_string_new("");

    settings_init ();
    commands_hash ();

    if (always_insert_mode)
        insert_mode = TRUE;

    GtkWidget* vbox = gtk_vbox_new (FALSE, 0);
    if (status_top)
        gtk_box_pack_start (GTK_BOX (vbox), create_mainbar (), FALSE, TRUE, 0);
    gtk_box_pack_start (GTK_BOX (vbox), create_browser (), TRUE, TRUE, 0);
    if (!status_top)
        gtk_box_pack_start (GTK_BOX (vbox), create_mainbar (), FALSE, TRUE, 0);

    main_window = create_window ();
    gtk_container_add (GTK_CONTAINER (main_window), vbox);

    load_uri (web_view, uri);

    gtk_widget_grab_focus (GTK_WIDGET (web_view));
    gtk_widget_show_all (main_window);
    xwin = GDK_WINDOW_XID (GTK_WIDGET (main_window)->window);
    printf("window_id %i\n",(int) xwin);
    printf("pid %i\n", getpid ());
    printf("name: %s\n", instance_name);

    scbar_v = (GtkScrollbar*) gtk_vscrollbar_new (NULL);
    bar_v = gtk_range_get_adjustment((GtkRange*) scbar_v);
    scbar_h = (GtkScrollbar*) gtk_hscrollbar_new (NULL);
    bar_h = gtk_range_get_adjustment((GtkRange*) scbar_h);
    gtk_widget_set_scroll_adjustments ((GtkWidget*) web_view, bar_h, bar_v);

    if (!show_status)
        gtk_widget_hide(mainbar);

    if (fifo_dir)
        create_fifo ();
    if (socket_dir)
        create_socket();

    gtk_main ();

    g_string_free(keycmd, TRUE);

    if (fifo_dir)
        unlink (fifo_path);
    if (socket_dir)
        unlink (socket_path);

    g_hash_table_destroy(bindings);
    g_hash_table_destroy(commands);
    return 0;
}
Example #29
0
int main(int argc, char **argv)
{
	GOptionContext *context;
	GError *error = NULL;
	DBusConnection *conn;
	DBusError err;
	guint watch;
	struct sigaction sa;

#ifdef NEED_THREADS
	if (g_thread_supported() == FALSE)
		g_thread_init(NULL);
#endif

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

	if (g_option_context_parse(context, &argc, &argv, &error) == FALSE) {
		if (error != NULL) {
			g_printerr("%s\n", error->message);
			g_error_free(error);
		} else
			g_printerr("An unknown error occurred\n");
		exit(1);
	}

	g_option_context_free(context);

	if (option_version == TRUE) {
		printf("%s\n", VERSION);
		exit(0);
	}

	main_loop = g_main_loop_new(NULL, FALSE);

#ifdef NEED_THREADS
	if (dbus_threads_init_default() == FALSE) {
		fprintf(stderr, "Can't init usage of threads\n");
		exit(1);
	}
#endif

	dbus_error_init(&err);

	conn = g_dbus_setup_bus(DBUS_BUS_SYSTEM, NULL, &err);
	if (conn == NULL) {
		if (dbus_error_is_set(&err) == TRUE) {
			fprintf(stderr, "%s\n", err.message);
			dbus_error_free(&err);
		} else
			fprintf(stderr, "Can't register with system bus\n");
		exit(1);
	}

	g_dbus_set_disconnect_function(conn, disconnect_callback, NULL, NULL);

	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = sig_term;
	sigaction(SIGINT, &sa, NULL);
	sigaction(SIGTERM, &sa, NULL);

	watch = g_dbus_add_service_watch(conn, OFONO_SERVICE,
				ofono_connect, ofono_disconnect, NULL, NULL);

	g_main_loop_run(main_loop);

	g_dbus_remove_watch(conn, watch);

	if (ofono_running == TRUE)
		ofono_disconnect(conn, NULL);

	dbus_connection_unref(conn);

	g_main_loop_unref(main_loop);

	return 0;
}
Example #30
0
int main(int argc, char **argv)
{
    if (initDecoderWithFile(filename))
        return -1;

    init_queue(&video_pkt_queue); //初始化视频数据包队列
    init_queue(&video_pic_queue); //初始化视频图像队列
    init_queue(&audio_pkt_queue);
    init_queue(&audio_sam_queue);
    
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);//设置线程分离属性

    //文件处理线程
    if (0 != pthread_create(&file_tid, &attr, demux, (void*)filename))
        printf("create file handler thread failed!\n");

    //视频解码线程
    if (0 != pthread_create(&dec_tid, &attr, video_decoder, NULL))
        printf("create decode thread failed!\n");

    if (0 != pthread_create(&audio_dec_tid, &attr, audio_decoder, NULL))
        printf("create audio decode thread failed!\n");

    if (0 != pthread_create(&audio_render_tid, &attr, audio_player, NULL))
        printf("create audio render thread failed!\n");

    /*以下是Gtk界面相关代码*/
    if (!g_thread_supported())
        g_thread_init(NULL);

    gdk_threads_init();
    gdk_threads_enter();

    GtkWidget *main_win;//主窗口
    //GtkWidget *drawable;//图像绘制区域
    gtk_init(&argc, &argv);

    char win_title[100];
    sprintf(win_title, "AniPlayer--by Excalibur : %s", filename);
    main_win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title(GTK_WINDOW(main_win), win_title);
    GtkWidget *drawable = gtk_drawing_area_new();

    gtk_container_add(GTK_CONTAINER(main_win), drawable);
    g_signal_connect(G_OBJECT(main_win), "delete-event", G_CALLBACK(exit_clean), NULL);
    //gtk_signal_connect(GTK_OBJECT(drawable), "expose-event", G_CALLBACK(on_darea_expose), NULL);

    gtk_widget_show_all(main_win);

    gtk_widget_set_size_request(drawable, g_player_ctx->width, g_player_ctx->height);

    //关闭自动刷新和双缓冲
    gtk_widget_set_app_paintable(drawable, TRUE);
    gtk_widget_set_double_buffered(drawable, FALSE);//此乃大坑,之前没disable掉一直刷白屏

    time_out = gtk_timeout_add(40, GSourceFunc(on_timer), drawable);

    gtk_main();

    gdk_threads_leave();
    
    _CrtDumpMemoryLeaks();

    //getchar();
    return 0;
}