示例#1
0
void CTreeViewGames::setNameFilter(Glib::ustring p_str) {
    int l_ind;

    // La aplicación del filtro dependerá de esta variable
    m_apply_filter_regex = (p_str != "");

    // Crearemos la expresión regular solo si es necesario
    if(m_apply_filter_regex) {
        // Escapamos caracteres especiales en la cadena y añadimos marcador de inicio
        p_str = "^" + Glib::Regex::escape_string(p_str);
        // Restauramos las apariciones de * para permitir la sustitución de 0 o
        // más caracteres
        l_ind = p_str.find("\\*");
        while(l_ind > -1) {
            p_str = p_str.replace(l_ind, 2, ".*");
            l_ind = p_str.find("\\*", l_ind + 1);
        }
        // Restauramos las apariciones de ? para permitir la sustitución de 0 o
        // 1 caracter
        l_ind = p_str.find("\\?");
        while(l_ind > -1) {
            p_str = p_str.replace(l_ind, 2, ".?");
            l_ind = p_str.find("\\?", l_ind + 1);
        }

        // Creamos la expresión regular para el filtrado por nombre
        m_filter_regex = Glib::Regex::create(p_str, Glib::REGEX_CASELESS|Glib::REGEX_OPTIMIZE);
    }

    m_filter_list->refilter();
}
示例#2
0
bool Document::matchesSearch (Glib::ustring const &search)
{
    /* This is a bit of a hack, I guess, but it's a low-impact way of 
     * implementing the change. If the search term contains a space, I 
     * iteratively decompose it into substrings and pass those onto
     * this function. If anything doesn't match, we return a failure.
     */
    if (search.find(' ') != Glib::ustring::npos) {
        Glib::ustring::size_type p1 = 0;
        Glib::ustring::size_type p2;

        do {

            /* Find the next space in the string, if any.
             */
            p2 = search.find(' ', p1);

            /* Extract the appropriate substring.
             */
            Glib::ustring const searchTerm = search.substr(p1, p2);

            /* If the term is empty, ignore it and move on. It might just be a 
             * trailing or duplicate space character.
             */
            if (searchTerm.empty()) {
                break;
            }

            /* Now that we have the substring, which is guaranteed to be
             * free of spaces, we can pass it recursively into this function.
             * If the term does NOT match, fail the entire comparison right away.
             */
            if (!matchesSearch(searchTerm)) {
                return false;
            }

            p1 = p2 + 1;		/* +1 to skip over the space */

        } while (p2 != Glib::ustring::npos); /* Terminate at end of string */
        return true;		/* All matched, so OK. */
    }

    Glib::ustring const searchNormalised = search.casefold();

    FieldMap fields = getFields ();
    FieldMap::iterator fieldIter = fields.begin ();
    FieldMap::iterator const fieldEnd = fields.end ();
    for (; fieldIter != fieldEnd; ++fieldIter) {
        if (fieldIter->second.casefold().find(searchNormalised) != Glib::ustring::npos)
            return true;
    }

    if (notes_.casefold().find(searchNormalised) != Glib::ustring::npos)
        return true;

    if (key_.casefold().find(searchNormalised) != Glib::ustring::npos)
        return true;

    return false;
}
示例#3
0
文件: parser.cpp 项目: ierofant/rise
void rise::parser::on_start_element(const Glib::ustring &_name,
                    		    const AttributeList &_attributes)
{
    Glib::ustring prefix, name = _name;
    auto pos = _name.find(':');
    if(pos != Glib::ustring::npos)
    {
	prefix = _name.substr(0, pos);
	name = _name.substr(pos + 1);
    }

    auto *el = doc.get_root_node();
    if(!el) el = doc.create_root_node();
    else el = context.top()->add_child(name, prefix);
    context.push(el);

    for(auto itr = _attributes.begin(); itr != _attributes.end(); ++itr)
    {
	Glib::ustring name = itr->name;
	Glib::ustring value = itr->value;
	auto pos = name.find(':');
	if(pos == Glib::ustring::npos)
	{
	    if(name == "xmlns") el->set_namespace_declaration(value);
	    else el->set_attribute(name, value);
	}
	else
	{
	    Glib::ustring prefix = name.substr(0, pos);
	    Glib::ustring suffix = name.substr(pos + 1);
	    if(prefix == "xmlns") el->set_namespace_declaration(value, suffix);
	    else el->set_attribute(suffix, value, prefix);
	}
    }
}
示例#4
0
Glib::ustring replace_in_string(Glib::ustring data, Glib::ustring toBeReplaced, Glib::ustring replace)
{
	guint pos = 0 ;
	int size = toBeReplaced.size() ;
	pos = data.find(toBeReplaced) ;
	while ( pos!= string::npos ) {
		data.replace(pos, size, replace) ;
		pos = data.find(toBeReplaced) ;
	}
	return data ;
}
示例#5
0
int mainWindow::callFunc(Glib::ustring str)
{
	Gtk::MessageDialog tempDialog(*this, "Error!");
	unsigned int leftBrace = str.find("(");
	unsigned int rightBrace = str.find(")");
	
	if(leftBrace > 2000000000)
	{
		tempDialog.set_secondary_text("Missing \"(\"");
		tempDialog.run();
		return SYNTAX_ERROR;
	}else if(rightBrace > 2000000000){
		tempDialog.set_secondary_text("Missing \")\"");
		tempDialog.run();
		return SYNTAX_ERROR;
	}else if(leftBrace > rightBrace){
		tempDialog.set_secondary_text("Syntax error near )");
		tempDialog.run();
		return SYNTAX_ERROR;
	}else if(leftBrace == 0){
		tempDialog.set_secondary_text("No function name given");
		tempDialog.run();
		return SYNTAX_ERROR;
	}else{
		Glib::ustring funcName = str.substr(0, leftBrace);
		Glib::ustring rawArg = str.substr(leftBrace+1, rightBrace-leftBrace-1);
		
		if(funcName == "del")
		{
			if(this->eqView->removeByName(rawArg) == false)
			{
				tempDialog.set_secondary_text("No function by that name!");
				tempDialog.run();
			}
			return FUNC_HANDLED;
		}else{
			if(this->eqView->getEqByName(funcName))
			{
				equation *tmpEq = this->eqView->getEqByName(funcName);
				double number = strtod(rawArg.c_str(),NULL);
				number = tmpEq->getYFromX(number);
				char buffer[600];
				sprintf(buffer,"%f",number);
				tempDialog.set_secondary_text(buffer);
				tempDialog.run();
				
			}else{
				return FUNC_NOT_FOUND;
			}
		}
	}
}
/*
 * Search function for widget.
 * Returns true if entered text matches contact address or nickname.
 */
bool ContactsTreeWidget::onSearchEqual(const Glib::RefPtr<Gtk::TreeModel>& model, gint column, const Glib::ustring& key, const Gtk::TreeModel::iterator& iter) {
  Gtk::TreeModel::Row row = *iter;
  if (row[columns.contactIndex] >= 20 && row[columns.contactIndex] != GROUP_INDEX_NOT_AUTHORIZED) {
    Glib::ustring x;
    x = row[columns.contactAddress];
    if (x.find(key) != Glib::ustring::npos) {
      return false;
    }
    x = row[columns.contactNickname];
    if (x.find(key) != Glib::ustring::npos) {
      return false;
    }
  }
  return true;
}
示例#7
0
void ViCommandMode::execute_search(const Glib::ustring &cmd, char begin )
{
    //
    //     /{pattern}/{offset}<CR>
    // search forward for the [count]'th occurrence of
    // {pattern} and go {offset} lines up or down.
    //
    int count = 1;              
    int offset = 0;
    Glib::ustring pattern;

    int idx = cmd.find( begin ); 
    if (idx > 0)
    {
        Glib::ustring rest = cmd.substr(idx+1);
        offset = convert<int>(rest);

        pattern = cmd.substr(0, idx);
    }
    else
    {
        pattern = cmd;
    }

    Direction dir = Forward;
    if (begin == '?')  
        dir = Backward;

    g_print("Searching for %s with offset %i\n", pattern.data(), offset);

    Editor *ed = Application::get()->get_current_editor();
    ed->search(pattern, dir);
    
}
示例#8
0
    /* compressed utf-8 table */
        0x20ac, /* 80 Euro. CP1252 from here on... */
        0x81,   /* 81 NA */
        0x201a, /* 82 */
        0x192,  /* 83 */
        0x201e, /* 84 */
        0x2026, /* 85 */
        0x2020, /* 86 */
        0x2021, /* 87 */
        0x2c6,  /* 88 */
        0x2030, /* 89 */
        0x160,  /* 8a */
        0x2039, /* 8b */
        0x152,  /* 8c */
        0x8d,   /* 8d NA */
        0x17d,  /* 8e */
        0x8f,   /* 8f NA */
        0x90,   /* 90 NA */
        0x2018, /* 91 */
        0x2019, /* 92 */
        0x201c, /* 93 */
        0x201d, /* 94 */
        0x2022, /* 95 */
        0x2013, /* 96 */
        0x2014, /* 97 */
        0x2dc,  /* 98 */
        0x2122, /* 99 */
        0x161,  /* 9a */
        0x203a, /* 9b */
        0x153,  /* 9c */
        0x9d,   /* 9d NA */
        0x17e,  /* 9e */
        0x178,  /* 9f */
        0xa0,   /* a0 */
        0xa1,   /* a1 */
        0xa2,   /* a2 */
        0xa3,   /* a3 */
        0x20ac  /* a4 ISO-8859-15 Euro. */
    };

    while (len) {
        if (G_UNLIKELY(*text >= 0x80) && G_UNLIKELY(*text <= 0xa4)) {
            int idx = *text - 0x80;
            output += lowtable[idx];
        } else {
            output += (gunichar)*text;    /* ascii/iso88591 maps directly */
        }

        text++;
        len--;
    }
    return output;
}/*}}}*/
void set_charset(Glib::ustring charset) {/*{{{*/
    charset = charset.uppercase();

    if (charset.find(' ') != Glib::ustring::npos)
        charset = charset.erase(charset.find(' '));

    if (charset.empty() || !charset.compare("SYSTEM")) {
        charset.clear();
    } else {
        try {
            Glib::IConv test("UTF-8", charset);
        } catch (...) {
            fprintf(stderr, "Charset '%s' isn't supported by your system - using system locale\n", charset.c_str());
            charset.clear();
        }
    }

    serverCharset = charset;
}/*}}}*/
std::string ustring_to_c(Glib::ustring input) {/*{{{*/
    std::string to_charset, converted;

    // check if input is already 7-bit
    if (input.is_ascii())
        return input;

    // try encoding using the selected charset, unless its some utf-8
    if (!serverCharset.empty() && serverCharset.find("UTF-8") == Glib::ustring::npos) {
        try {
            return Glib::convert(input, serverCharset, "UTF-8");
        } catch (...) {}
    }

    // try encoding using the locale charset, unless its some utf-8
    if (Glib::get_charset(to_charset) == true)
        to_charset = "ISO-8859-1";

    try {
        converted = Glib::convert_with_fallback(input, to_charset, "UTF-8", "?");
    } catch (...) {
        converted = input;
    }
    return converted;
}/*}}}*/
Glib::ustring NoteDirectoryWatcherApplicationAddin::get_id(const Glib::ustring & path)
{
  Glib::ustring dir_separator;
  dir_separator += G_DIR_SEPARATOR;
  int last_slash = sharp::string_last_index_of(path, dir_separator);
  int first_period = path.find(".", last_slash);

  return path.substr(last_slash + 1, first_period - last_slash - 1);
}
示例#10
0
    /* compressed utf-8 table */
        0x20ac, /* 80 Euro. CP1252 from here on... */
        0x81,   /* 81 NA */
        0x201a, /* 82 */
        0x192,  /* 83 */
        0x201e, /* 84 */
        0x2026, /* 85 */
        0x2020, /* 86 */
        0x2021, /* 87 */
        0x2c6,  /* 88 */
        0x2030, /* 89 */
        0x160,  /* 8a */
        0x2039, /* 8b */
        0x152,  /* 8c */
        0x8d,   /* 8d NA */
        0x17d,  /* 8e */
        0x8f,   /* 8f NA */
        0x90,   /* 90 NA */
        0x2018, /* 91 */
        0x2019, /* 92 */
        0x201c, /* 93 */
        0x201d, /* 94 */
        0x2022, /* 95 */
        0x2013, /* 96 */
        0x2014, /* 97 */
        0x2dc,  /* 98 */
        0x2122, /* 99 */
        0x161,  /* 9a */
        0x203a, /* 9b */
        0x153,  /* 9c */
        0x9d,   /* 9d NA */
        0x17e,  /* 9e */
        0x178,  /* 9f */
        0xa0,   /* a0 */
        0xa1,   /* a1 */
        0xa2,   /* a2 */
        0xa3,   /* a3 */
        0x20ac  /* a4 ISO-8859-15 Euro. */
    };

    while (len) {
        if (G_UNLIKELY(*text >= 0x80) && G_UNLIKELY(*text <= 0xa4)) {
            int idx = *text - 0x80;
            output += lowtable[idx];
        } else {
            output += (gunichar)*text;    /* ascii/iso88591 maps directly */
        }

        text++;
        len--;
    }
    return output;
}/*}}}*/
void set_charset(Glib::ustring charset) {/*{{{*/
    charset = charset.uppercase();

    if (charset.find(' ') != Glib::ustring::npos)
        charset = charset.erase(charset.find(' '));

    if (charset.empty() || !charset.compare("SYSTEM")) {
        charset.clear();
    } else {
        try {
            Glib::IConv test("UTF-8", charset);
        } catch (...) {
            fprintf(stderr, "Charset '%s' isn't supported by your system - using system locale\n", charset.c_str());
            charset.clear();
        }
    }

    serverCharset = charset;
}/*}}}*/
示例#11
0
/**
    Replace font family leaving style alone (if possible).
    @param fontSpec the given font
    @param newFamily
    @return the changed fontspec, if the property can not be set return an empty string
    The routine first searches for an exact match.
    If no exact match found, calls FontSpecificationBestMatch().
*/
Glib::ustring font_factory::ReplaceFontSpecificationFamily(const Glib::ustring & fontSpec, const Glib::ustring & newFamily)
{
    Glib::ustring newFontSpec;

    // Although we are using the string from pango_font_description_to_string for the
    // font specification, we definitely cannot just set the new family in the
    // PangoFontDescription structure and ask for a new string.  This is because
    // what constitutes a "family" in our own UI may be different from how Pango
    // sees it.

    // Find the PangoFontDescription associated with the old font specification string.
    PangoStringToDescrMap::iterator it = fontInstanceMap.find(fontSpec);


    if (it != fontInstanceMap.end()) {
        // Description found!

        // Make copy
        PangoFontDescription *descr = pango_font_description_copy((*it).second);

        // Grab the old UI Family string from the descr
        Glib::ustring uiFamily = GetUIFamilyString(descr);

        // Replace the UI Family name with the new family name
        std::size_t found = fontSpec.find(uiFamily);
        if (found != Glib::ustring::npos) {

            // Add comma to end of newFamily... commas at end don't hurt but are
            // required if the last part of a family name is a valid font style
            // (e.g. "Arial Black").
            Glib::ustring newFamilyComma = newFamily;
            if( *newFamilyComma.rbegin() != ',' ) {
                newFamilyComma += ",";
            }
            newFontSpec = fontSpec;
            newFontSpec.erase(found, uiFamily.size());
            newFontSpec.insert(found, newFamilyComma);

            // If the new font specification does not exist in the reference maps,
            // search for the next best match for the faces in that style
            it = fontInstanceMap.find(newFontSpec);
            if (it == fontInstanceMap.end()) {

                // Search for best match, empty string returned if not found.
                newFontSpec = FontSpecificationBestMatch( newFontSpec );

            }
        }

        pango_font_description_free(descr);
    }

    return newFontSpec;
}
示例#12
0
equation* mainWindow::createEqFromStr(Glib::ustring str)
{
	Gtk::MessageDialog tempDialog(*this, "Error!");
	unsigned int equalPos = commandLine->get_text().find("=");
	
	//check for = sign else give a error
	if(equalPos > 2000000000)
	{
		tempDialog.set_secondary_text("No \"=\" found");
		tempDialog.run();
		return 0;
	}else{
		//Now substring the str form equalPos
		Glib::ustring leftSide = str.substr(0, equalPos);
		
		//now find the function variable
		unsigned int firstBrace = leftSide.find("(");
		//if this is zero, no function name is given.
		if(firstBrace == 0)
		{
			tempDialog.set_secondary_text("No function name is given");
			tempDialog.run();
			return 0;
		}else{
			//if ( is not found error
			if(firstBrace > 2000000000)
			{
				tempDialog.set_secondary_text("Missing \"(\" in function name");
				tempDialog.run();
				return 0;
			}
			
			
			Glib::ustring afterBrace = leftSide.substr(firstBrace);
			if(afterBrace.length() != 3)
			{
				tempDialog.set_secondary_text("Syntax error in variable name");
				tempDialog.run();
				return 0;
			}
			
			Glib::ustring variableName = afterBrace.substr(1,1);
			Glib::ustring functionName = leftSide.substr(0, firstBrace);
			
			Glib::ustring rightSide = str.substr(equalPos+1);
			
			equation *tempEq = new equation();
			tempEq->setName(functionName);
			tempEq->setEquation(rightSide);
			tempEq->setVariable(variableName);
			return tempEq;
		}
	}
}
示例#13
0
void strTo(const Glib::ustring& p_str, T p_out){
	int l_pos;
	unsigned int l_oldpos;
	std::stringstream l_str;
	Q l_ret;

	// Si la cadena no contiene nada, terminamos
	if(p_str.size() == 0)
		return;

	// Puntero de cabecera y cola en la cadena
	l_oldpos = 0;
	l_pos = p_str.find("," , 0);
	// Si hay cadenas
	while(l_pos > -1){
		// Convertimos y añadimos la substring
		l_str.clear();
		l_str << p_str.substr(l_oldpos, l_pos - l_oldpos).c_str();
		l_str >> l_ret;
		*p_out++ = l_ret;

		// Saltamos , o ", "
		if(p_str[l_pos + 1] == ' ')
			l_oldpos = l_pos + 2;
		else
			l_oldpos = l_pos + 1;
		// Buscamos la siguiente ","
		l_pos = p_str.find("," , l_oldpos);
	}

	if(l_oldpos != p_str.size()){
		// Convertimos y añadimos la substring
		l_str.clear();
		l_str << p_str.substr(l_oldpos, p_str.size()).c_str();
		l_str >> l_ret;
		*p_out = l_ret;
	}
示例#14
0
unsigned long XGPacketBuilder::parse_number(Glib::ustring str)
{
        unsigned long l = 0;
        size_t n = str.find("0x");
        
        if (n != std::string::npos)
        {
                l = std::strtol(str.substr(n).c_str(), 0, 16);
        }
        else
        {
                l = std::strtol(str.c_str(), 0, 10);
        }
        
        return l;
}
void DimensionManager::addDimension() {
    Gtk::Dialog dialog(_("New Dimension"), true /*modal*/);
    // add dimension type combo box to the dialog
    Glib::RefPtr<Gtk::ListStore> refComboModel = Gtk::ListStore::create(comboModel);
    for (int i = 0x01; i < 0xff; i++) {
        Glib::ustring sType =
            dimTypeAsString(static_cast<gig::dimension_t>(i));
        if (sType.find("Unknown") != 0) {
            Gtk::TreeModel::Row row = *(refComboModel->append());
            row[comboModel.m_type_id]   = i;
            row[comboModel.m_type_name] = sType;
        }
    }
    Gtk::Table table(2, 2);
    Gtk::Label labelDimType(_("Dimension:"), Gtk::ALIGN_START);
    Gtk::ComboBox comboDimType;
    comboDimType.set_model(refComboModel);
    comboDimType.pack_start(comboModel.m_type_id);
    comboDimType.pack_start(comboModel.m_type_name);
    Gtk::Label labelZones(_("Zones:"), Gtk::ALIGN_START);
    table.attach(labelDimType, 0, 1, 0, 1);
    table.attach(comboDimType, 1, 2, 0, 1);
    table.attach(labelZones, 0, 1, 1, 2);
    dialog.get_vbox()->pack_start(table);

    // number of zones: use a combo box with fix values for gig
    // v2 and a spin button for v3
    Gtk::ComboBoxText comboZones;
    Gtk::SpinButton spinZones;
    bool version2 = false;
    if (region) {
        gig::File* file = (gig::File*)region->GetParent()->GetParent();
        version2 = file->pVersion && file->pVersion->major == 2;
    }
    if (version2) {
        for (int i = 1; i <= 5; i++) {
            char buf[3];
            sprintf(buf, "%d", 1 << i);
#if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 24) || GTKMM_MAJOR_VERSION < 2
            comboZones.append_text(buf);
#else
            comboZones.append(buf);
#endif
        }
        table.attach(comboZones, 1, 2, 1, 2);
    } else {
        spinZones.set_increments(1, 8);
        spinZones.set_numeric(true);
        spinZones.set_range(2, 128);
        spinZones.set_value(2);
        table.attach(spinZones, 1, 2, 1, 2);
    }

    dialog.add_button(_("_OK"), 0);
    dialog.add_button(_("_Cancel"), 1);
    dialog.show_all_children();

    if (!dialog.run()) { // OK selected ...
        Gtk::TreeModel::iterator iterType = comboDimType.get_active();
        if (!iterType) return;
        Gtk::TreeModel::Row rowType = *iterType;
        if (!rowType) return;
        int iTypeID = rowType[comboModel.m_type_id];
        gig::dimension_t type = static_cast<gig::dimension_t>(iTypeID);
        gig::dimension_def_t dim;
        dim.dimension = type;

        if (version2) {
            if (comboZones.get_active_row_number() < 0) return;
            dim.bits = comboZones.get_active_row_number() + 1;
            dim.zones = 1 << dim.bits;
        } else {
            dim.zones = spinZones.get_value_as_int();
            dim.bits = zoneCountToBits(dim.zones);
        }

        // assemble the list of regions where the selected dimension shall be
        // added to
        std::vector<gig::Region*> vRegions;
        if (allRegions()) {
            gig::Instrument* instr = (gig::Instrument*)region->GetParent();
            for (gig::Region* rgn = instr->GetFirstRegion(); rgn; rgn = instr->GetNextRegion()) {
                if (!rgn->GetDimensionDefinition(type)) vRegions.push_back(rgn);
            }
        } else vRegions.push_back(region);
            
        std::set<Glib::ustring> errors;

        for (uint iRgn = 0; iRgn < vRegions.size(); ++iRgn) {
            gig::Region* region = vRegions[iRgn];
            try {
                printf(
                    "Adding dimension (type=0x%x, bits=%d, zones=%d)\n",
                    dim.dimension, dim.bits, dim.zones
                );
                // notify everybody that we're going to update the region
                region_to_be_changed_signal.emit(region);
                // add the new dimension to the region
                // (implicitly creates new dimension regions)
                region->AddDimension(&dim);
                // let everybody know there was a change
                region_changed_signal.emit(region);
            } catch (RIFF::Exception e) {
                // notify that the changes are over (i.e. to avoid dead locks)
                region_changed_signal.emit(region);
                Glib::ustring txt = _("Could not add dimension: ") + e.Message;
                if (vRegions.size() == 1) {
                    // show error message directly
                    Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
                    msg.run();
                } else {
                    // remember error, they are shown after all regions have been processed
                    errors.insert(txt);
                }
            }
        }
        // update all GUI elements
        refreshManager();

        if (!errors.empty()) {
            Glib::ustring txt = _(
                "The following errors occurred while trying to create the dimension on all regions:"
            );
            txt += "\n\n";
            for (std::set<Glib::ustring>::const_iterator it = errors.begin();
                 it != errors.end(); ++it)
            {
                txt += "-> " + *it + "\n";
            }
            txt += "\n";
            txt += _(
                "You might also want to check the console for further warnings and "
                "error messages."
            );
            Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
            msg.run();
        }
    }
}
void DimensionManager::onColumnClicked() {
    printf("DimensionManager::onColumnClicked()\n");

    //FIXME: BUG: this method is currently very unreliably called, it should actually be called when the user selects another column, it is ATM however also called when the table content changed programmatically causing the dialog below to popup at undesired times !

    //HACK: Prevents that onColumnClicked() gets called multiple times or at times where it is not desired
    if (ignoreColumnClicked) {
        ignoreColumnClicked = false;
        return;
    }
#if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 18) || GTKMM_MAJOR_VERSION > 2
    // prevents app to crash if this dialog is closed
    if (!get_visible())
        return;
#else
# warning Your GTKMM version is too old; dimension manager dialog might crash when changing a dimension type !
#endif

#if (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION >= 8) || GTKMM_MAJOR_VERSION > 3
    if (!is_visible()) return;
#endif

    Gtk::TreeModel::Path path;
    Gtk::TreeViewColumn* focus_column;
    treeView.get_cursor(path, focus_column);
    //const int row = path[0];
    if (focus_column == treeView.get_column(0)) {
        Gtk::TreeModel::iterator it = treeView.get_model()->get_iter(path);
        if (!it) return;
        Gtk::TreeModel::Row row = *it;
        gig::dimension_t oldType = row[tableModel.m_type];

        Gtk::Dialog dialog(_("Change Dimension"), true /*modal*/);
        int oldTypeIndex = -1;
        Glib::RefPtr<Gtk::ListStore> refComboModel = Gtk::ListStore::create(comboModel);
        for (int i = 0x01, count = 0; i < 0xff; i++) {
            Glib::ustring sType =
                dimTypeAsString(static_cast<gig::dimension_t>(i));
            if (i == oldType) oldTypeIndex = count;
            if (sType.find("Unknown") != 0) {
                Gtk::TreeModel::Row row = *(refComboModel->append());
                row[comboModel.m_type_id]   = i;
                row[comboModel.m_type_name] = sType;
                count++;
            }
        }
        Gtk::Table table(1, 2);
        Gtk::Label labelDimType(_("Dimension:"), Gtk::ALIGN_START);
        Gtk::ComboBox comboDimType;
        comboDimType.set_model(refComboModel);
        comboDimType.pack_start(comboModel.m_type_id);
        comboDimType.pack_start(comboModel.m_type_name);
        table.attach(labelDimType, 0, 1, 0, 1);
        table.attach(comboDimType, 1, 2, 0, 1);
        dialog.get_vbox()->pack_start(table);

        dialog.add_button(_("_OK"), 0);
        dialog.add_button(_("_Cancel"), 1);
        dialog.show_all_children();
        
        comboDimType.set_active(oldTypeIndex);

        if (!dialog.run()) { // OK selected ...
            ignoreColumnClicked = true;
            Gtk::TreeModel::iterator iterType = comboDimType.get_active();
            if (!iterType) return;
            Gtk::TreeModel::Row rowType = *iterType;
            if (!rowType) return;
            int iTypeID = rowType[comboModel.m_type_id];
            gig::dimension_t newType = static_cast<gig::dimension_t>(iTypeID);
            if (newType == oldType) return;
            //printf("change 0x%x -> 0x%x\n", oldType, newType);

            // assemble the list of regions where the selected dimension type
            // shall be changed
            std::vector<gig::Region*> vRegions;
            if (allRegions()) {
                gig::Instrument* instr = (gig::Instrument*)region->GetParent();
                for (gig::Region* rgn = instr->GetFirstRegion(); rgn; rgn = instr->GetNextRegion()) {
                    if (rgn->GetDimensionDefinition(oldType)) vRegions.push_back(rgn);
                }
            } else vRegions.push_back(region);

            std::set<Glib::ustring> errors;

            for (uint iRgn = 0; iRgn < vRegions.size(); ++iRgn) {
                gig::Region* region = vRegions[iRgn];
                try {
                    // notify everybody that we're going to update the region
                    region_to_be_changed_signal.emit(region);
                    // change the dimension type on that region
                    region->SetDimensionType(oldType, newType);
                    // let everybody know there was a change
                    region_changed_signal.emit(region);
                } catch (RIFF::Exception e) {
                    // notify that the changes are over (i.e. to avoid dead locks)
                    region_changed_signal.emit(region);
                    Glib::ustring txt = _("Could not alter dimension: ") + e.Message;
                    if (vRegions.size() == 1) {
                        // show error message directly
                        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
                        msg.run();
                    } else {
                        // remember error, they are shown after all regions have been processed
                        errors.insert(txt);
                    }
                }
            }
            // update all GUI elements
            refreshManager();

            if (!errors.empty()) {
                Glib::ustring txt = _(
                    "The following errors occurred while trying to change the dimension type on all regions:"
                );
                txt += "\n\n";
                for (std::set<Glib::ustring>::const_iterator it = errors.begin();
                    it != errors.end(); ++it)
                {
                    txt += "-> " + *it + "\n";
                }
                txt += "\n";
                txt += _(
                    "You might also want to check the console for further warnings and "
                    "error messages."
                );
                Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
                msg.run();
            }
        }
    }
}
示例#17
0
Glib::ustring Document::generateKey ()
{
	// Ideally Chambers06
	// If not then pap104
	// If not then Unnamed-5
	Glib::ustring name;

	Glib::ustring::size_type const maxlen = 14;

	if (!bib_.getAuthors().empty ()) {
		Glib::ustring year = bib_.getYear ();
		if (year.size() == 4)
			year = year.substr (2,3);

		Glib::ustring authors = bib_.getAuthors ();

		Glib::ustring::size_type comma = authors.find (",");
		Glib::ustring::size_type space = authors.find (" ");
		Glib::ustring::size_type snip = Glib::ustring::npos;

		if (comma != Glib::ustring::npos)
			snip = comma;
		if (space != Glib::ustring::npos && space < comma)
			snip = space;

		if (snip != Glib::ustring::npos)
			authors = authors.substr(0, snip);


		if (authors.size() > maxlen - 2) {
			authors = authors.substr(0, maxlen - 2);
		}

		// Should:
		// Truncate it at the first "et al", "and", or ","

		name = authors + year;
	} else if (!filename_.empty ()) {
		Glib::ustring filename = Gio::File::create_for_uri(filename_)->query_info()->get_display_name();

		Glib::ustring::size_type periodpos = filename.find_last_of (".");
		if (periodpos != std::string::npos) {
			filename = filename.substr (0, periodpos);
		}

		name = filename;
		if (name.size() > maxlen) {
			name = name.substr(0, maxlen);
		}

	} else {
		name = defaultKey_;
	}

	// Don't confuse LaTeX
	name = Utility::strip (name, " ");
	name = Utility::strip (name, "&");
	name = Utility::strip (name, "$");
	name = Utility::strip (name, "%");
	name = Utility::strip (name, "#");
	name = Utility::strip (name, "_");
	name = Utility::strip (name, "{");
	name = Utility::strip (name, "}");
	name = Utility::strip (name, ",");
	name = Utility::strip (name, "@");

	return name;
}
bool FileManager::OpenFiles(int argc, char **argv)
	{
#ifdef DEBUG
std::cout << "OPENFILES: OpenFiles called \n";
#endif // DEBUG

	// makes sure we're dealing with a clean slate
	filenames.clear();
	numfiles = 0;
	cwd_checked = false;
	initialised = false;
	
	/* //	if we have initialised already we're being called from the file selector and will
	//	accept new files now, let's set initialised and cwd_checked to 'false' and clear our file list
	if( initialised == true )
		{
		numfiles = 0;
		cwd_checked = false;
		initialised = false;
		} // */
		
#ifdef DEBUG
std::cout << "OPENFILES: get_current_dir_name(): " << get_current_dir_name() << std::endl;
#endif // DEBUG
		
	if( argc > 1 )
		{
		for(int i = 1; i < argc; i++)
			{
			if( stat(argv[i], &filemode) != 0 )
				{
				std::cout << GT( "OPENFILES: Stat Error! Level 1 " ) << argv[i] << std::endl;
				}
			else
				{
				Glib::ustring filename;
				
				// Resolve any ".." and double / in the filename and make the filename absolute
				if( Glib::path_is_absolute( argv[i] ) )
					filename = argv[i] ;
				else
					filename = (Glib::ustring)get_current_dir_name() + "/" + (Glib::ustring)argv[i];
				
				while( filename.find("..") != Glib::ustring::npos )
					{
					filename.erase( 
						filename.rfind( '/', filename.find("..")-2), 
						filename.find("..")+2 - filename.rfind( '/', filename.find("..")-2) );
					}
				while( filename.find("//") != Glib::ustring::npos )
					filename.erase(
						filename.find("//"), filename.find("//")+1 );
				if( filename[ filename.length()-1 ] == '/' )
					filename.erase( filename.length()-1, filename.length() );
					
					
				if(filemode.st_mode & S_IFREG )  // if the file is a regular file
					{
					if( filter_filename(filename) ) // and seems to be a supported format
						{
						#ifdef DEBUG
						std::cout << "FILEMANAGER: curent argv: " << filename << std::endl;
						std::cout << "FILEMANAGER: dirname from argv: " << Glib::path_get_dirname( filename ) << std::endl;
						std::cout << "FILEMANAGER: curent dir: " << get_current_dir_name() << std::endl;
						#endif
						  
						filenames.insert( filenames.end(), filename ); // insert into list
						numfiles++;
						}
					}
				else if(filemode.st_mode & S_IFDIR) 			// if the file is a directory
					{
					cwd_checked = true;
					if((currdir = opendir(filename.c_str())) != NULL) 	// open it
						{
						while( (dirinfo = readdir(currdir)) != NULL ) // run through it
							{
							// don't forget, we're doing some string to char* conversions here 
							// here to avoid memory errors.. Glib::ustring is nice!
							Glib::ustring currfile(filename); 				// store the directory name
							currfile += '/'; 							// add a directory dash
							currfile += dirinfo->d_name; 				// add the filename
							if(stat(currfile.c_str(), &filemode) != 0)  // check for filetype
								{
								std::cout << GT( "OPENFILES: Stat Error! Level 2 " ) << currfile << std::endl;
								}
							else
								{
								if( filemode.st_mode & S_IFREG && filter_filename(currfile) ) // as above
									{
					                filenames.insert( filenames.end(), currfile ); // insert into list
									numfiles++;
									}
								}
							}
						closedir(currdir);
						}
					}
				}
			}
		filenames.sort();
		file_iterator = filenames.begin();
		}

	// when only one file was openened, we'll scan through its directory
	// and give the user control over the files
	if ( numfiles == 1 && cwd_checked == false )
		{
			cwd_checked = true;

			Glib::ustring tempfilename = *file_iterator;
			
			// prepare the file's directory name in such a way that we can pass
			// it to OpenFiles() which operates on argc/argv	
			char *dirname = new char[ (Glib::path_get_dirname( *file_iterator )).length() + 1  ];
			strcpy( dirname, (Glib::path_get_dirname( *file_iterator )).c_str() );

			char *arguments[] = { "empty" , dirname };

			// we erase the list of filenames as otherwise we would have one file twice
			filenames.clear();
			numfiles = 0;

			// now let's open the file's directory and check its contents
			OpenFiles( 2, arguments );

			// now we have a new set of files in the list, we have to find the file that
			// the user actually wanted to open!

			std::list<Glib::ustring>::iterator end = filenames.end();
			while( file_iterator != end )
				{
				#ifdef DEBUG
				std::cout << "OPENFILES: Looking for " << tempfilename << " in " << (*file_iterator) << std::endl;
				#endif
				if( (*file_iterator).find( tempfilename ) != Glib::ustring::npos )
					{
					break; // break out of the while loop if we find the filename
					}
				file_iterator++;
				}
			// when we have reached the end while looking, let's just load the first image!
			// as that means that either we didn't recognize the filename in our search above
			// or there was only one file in the directory after all!
			if( file_iterator == end )
				file_iterator = filenames.begin();

			#ifdef DEBUG
			std::cout << "OPENFILES: Deleting temporary dirname. \n";
			#endif
			
			delete[] dirname;
		}	
		
	// everything seems to have worked out alright, let's return true
	if ( numfiles > 0 )
		{
		#ifdef DEBUG
		std::cout << "OPENFILES: We're all set to go and we have " << numfiles << " files." << std::endl; 
		#endif // DEBUG
		return true;
		}
		// we did not have sufficient arguments or we have made some mistake, return false
	else
		{
		#ifdef DEBUG
		std::cout << "OPENFILES: We have " << numfiles << " files." << std::endl;
		#endif
		return false;
		}	

	}
// for speed we assume that correctly named files are actually
// images and invoke magic only if the filename is inconclusive
bool FileManager::filter_filename(Glib::ustring filename)
	{
	// check the filename first
	if( filename.find(".jpg") != Glib::ustring::npos ||
		filename.find(".JPG") != Glib::ustring::npos ||
		filename.find(".gif") != Glib::ustring::npos ||
		filename.find(".GIF") != Glib::ustring::npos ||
		filename.find(".png") != Glib::ustring::npos ||
		filename.find(".PNG") != Glib::ustring::npos ||
		filename.find(".bmp") != Glib::ustring::npos ||
		filename.find(".BMP") != Glib::ustring::npos ||
		filename.find(".xpm") != Glib::ustring::npos ||
		filename.find(".XPM") != Glib::ustring::npos ||
		filename.find(".pcx") != Glib::ustring::npos ||
		filename.find(".PCX") != Glib::ustring::npos ||
		filename.find(".pgm") != Glib::ustring::npos ||
		filename.find(".PGM") != Glib::ustring::npos ||
		filename.find(".ppm") != Glib::ustring::npos ||
		filename.find(".PPM") != Glib::ustring::npos ||
		filename.find(".tiff") != Glib::ustring::npos ||
		filename.find(".TIFF") != Glib::ustring::npos ||
		filename.find(".tif") != Glib::ustring::npos ||
		filename.find(".TIF") != Glib::ustring::npos ||
		filename.find(".tga") != Glib::ustring::npos ||
		filename.find(".TGA") != Glib::ustring::npos ||
		filename.find(".pbm") != Glib::ustring::npos ||
		filename.find(".PBM") != Glib::ustring::npos ||
		filename.find(".ppm") != Glib::ustring::npos ||
		filename.find(".PPM") != Glib::ustring::npos ||
		filename.find(".svg") != Glib::ustring::npos ||
		filename.find(".SVG") != Glib::ustring::npos )
		return true;
	
	else
		{
		// if we haven't returned yet, do file magic
		if( magic_file( cookie, filename.c_str() ) != NULL )
			{
			result = magic_file(cookie, filename.c_str() );
	#ifdef DEBUG
			std::cout << filename << " " << result << std::endl;
	#endif // DEBUG
			}
		else
			std::cout << GT( "FILTER_FILENAME: The file type could not be determined: " ) << filename << std::endl;

		// SVG is an xml format, libmagic gives XML, so we check the filename!
		// EPS sometimes holds TIFF images, we prevent the program from opening them!

		if( result.find("JPEG") != Glib::ustring::npos 	||
			result.find("GIF") != Glib::ustring::npos	||
			result.find("PNG") != Glib::ustring::npos	||
			result.find("PC bitmap") != Glib::ustring::npos ||
			result.find("PCX") != Glib::ustring::npos ||
			result.find("PGM") != Glib::ustring::npos	||
			result.find("PPM") != Glib::ustring::npos	||
			result.find("TIFF") != Glib::ustring::npos && result.find("EPS") == Glib::ustring::npos	||
			result.find("X pixmap image text") != Glib::ustring::npos	||
			result.find("Targa") != Glib::ustring::npos	||
			result.find("PBM") != Glib::ustring::npos	||
			result.find("SVG") != Glib::ustring::npos	||
			result.find("PPM") != Glib::ustring::npos ||
			filename.find(".svg") != Glib::ustring::npos ||
			filename.find(".SVG") != Glib::ustring::npos        )
			return true;
		else
			return false;
		}
	}
示例#20
0
文件: Loader.cpp 项目: EQ4/lad
/** Load (create) all objects from RDF into the engine.
 *
 * @param uri URI of machine (resolvable URI to an RDF document).
 * @return Loaded Machine.
 */
SPtr<Machine>
Loader::load(const Glib::ustring& uri)
{
	using Glib::ustring;

	ustring document_uri = uri;

	// If "URI" doesn't contain a colon, try to resolve as a filename
	if (uri.find(":") == ustring::npos) {
		document_uri = "file://" + document_uri;
	}

	cout << "Loading " << document_uri << endl;

	TimeUnit beats(TimeUnit::BEATS, MACHINA_PPQN);

	SPtr<Machine> machine(new Machine(beats));

	typedef std::map<Sord::Node, SPtr<Node> > Created;
	Created created;

	Sord::URI   base_uri(_rdf_world, document_uri);
	Sord::Model model(_rdf_world, document_uri);

	SerdEnv* env = serd_env_new(base_uri.to_serd_node());
	model.load_file(env, SERD_TURTLE, document_uri);
	serd_env_free(env);

	Sord::Node nil;

	Sord::URI machina_SelectorNode(_rdf_world, MACHINA_NS_SelectorNode);
	Sord::URI machina_duration(_rdf_world, MACHINA_NS_duration);
	Sord::URI machina_edge(_rdf_world, MACHINA_NS_arc);
	Sord::URI machina_head(_rdf_world, MACHINA_NS_head);
	Sord::URI machina_node(_rdf_world, MACHINA_NS_node);
	Sord::URI machina_onEnter(_rdf_world, MACHINA_NS_onEnter);
	Sord::URI machina_onExit(_rdf_world, MACHINA_NS_onExit);
	Sord::URI machina_probability(_rdf_world, MACHINA_NS_probability);
	Sord::URI machina_start(_rdf_world, MACHINA_NS_start);
	Sord::URI machina_tail(_rdf_world, MACHINA_NS_tail);
	Sord::URI rdf_type(_rdf_world, MACHINA_URI_RDF "type");

	Sord::Node subject = base_uri;

	// Get start node ID (but re-use existing start node)
	Sord::Iter i = model.find(subject, machina_start, nil);
	if (i.end()) {
		cerr << "error: Machine has no start node" << std::endl;
	}
	created[i.get_object()] = machine->initial_node();

	// Get remaining nodes
	for (Sord::Iter i = model.find(subject, machina_node, nil); !i.end(); ++i) {
		const Sord::Node& id = i.get_object();
		if (created.find(id) != created.end()) {
			cerr << "warning: Machine lists the same node twice" << std::endl;
			continue;
		}

		// Create node
		Sord::Iter d = model.find(id, machina_duration, nil);
		SPtr<Node> node(new Node(TimeStamp(beats, d.get_object().to_float())));
		machine->add_node(node);
		created[id] = node;

		node->set_enter_action(
			load_action(model, model.get(id, machina_onEnter, nil)));
		node->set_exit_action(
			load_action(model, model.get(id, machina_onExit, nil)));
	}

	// Get arcs
	for (Sord::Iter i = model.find(subject, machina_edge, nil); !i.end(); ++i) {
		Sord::Node edge = i.get_object();
		Sord::Iter t    = model.find(edge, machina_tail, nil);
		Sord::Iter h    = model.find(edge, machina_head, nil);
		Sord::Iter p    = model.find(edge, machina_probability, nil);

		Sord::Node tail        = t.get_object();
		Sord::Node head        = h.get_object();
		Sord::Node probability = p.get_object();

		float prob = probability.to_float();

		Created::iterator tail_i = created.find(tail);
		Created::iterator head_i = created.find(head);

		if (tail_i != created.end() && head_i != created.end()) {
			const SPtr<Node> tail = tail_i->second;
			const SPtr<Node> head = head_i->second;
			tail->add_edge(SPtr<Edge>(new Edge(tail, head, prob)));
		} else {
			cerr << "warning: Ignored edge between unknown nodes "
			     << tail << " -> " << head << endl;
		}
	}

	if (machine && !machine->nodes().empty()) {
		machine->reset(NULL, machine->time());
		return machine;
	} else {
		return SPtr<Machine>();
	}
}
示例#21
0
static void sp_image_image_edit(GtkMenuItem *menuitem, SPAnchor *anchor)
{
    SPObject* obj = anchor;
    Inkscape::XML::Node *ir = obj->getRepr();
    const gchar *href = ir->attribute("xlink:href");

    GError* errThing = 0;
    Glib::ustring cmdline = getImageEditorName();
    Glib::ustring name;
    Glib::ustring fullname;
    
#ifdef WIN32
    // g_spawn_command_line_sync parsing is done according to Unix shell rules,
    // not Windows command interpreter rules. Thus we need to enclose the
    // executable path with sigle quotes.
    int index = cmdline.find(".exe");
    if ( index < 0 ) index = cmdline.find(".bat");
    if ( index < 0 ) index = cmdline.find(".com");
    if ( index >= 0 ) {
        Glib::ustring editorBin = cmdline.substr(0, index + 4).c_str();
        Glib::ustring args = cmdline.substr(index + 4, cmdline.length()).c_str();
        editorBin.insert(0, "'");
        editorBin.append("'");
        cmdline = editorBin;
        cmdline.append(args);
    } else {
        // Enclose the whole command line if no executable path can be extracted.
        cmdline.insert(0, "'");
        cmdline.append("'");
    }
#endif

    if (strncmp (href,"file:",5) == 0) {
    // URI to filename conversion
      name = g_filename_from_uri(href, NULL, NULL);
    } else {
      name.append(href);
    }


    if (Glib::path_is_absolute(name)) {
        fullname = name;
    } else if (SP_ACTIVE_DOCUMENT->getBase()) {
        fullname = Glib::build_filename(SP_ACTIVE_DOCUMENT->getBase(), name);
    } else {
        fullname = Glib::build_filename(Glib::get_current_dir(), name);
    }


    cmdline.append(" '");
    cmdline.append(fullname.c_str());
    cmdline.append("'");

    //g_warning("##Command line: %s\n", cmdline.c_str());

    g_spawn_command_line_async(cmdline.c_str(),
                  &errThing); 

    if ( errThing ) {
        g_warning("Problem launching editor (%d). %s", errThing->code, errThing->message);
        SPDesktop *desktop = (SPDesktop*)gtk_object_get_data(GTK_OBJECT(menuitem), "desktop");
        desktop->messageStack()->flash(Inkscape::ERROR_MESSAGE, errThing->message);
        g_error_free(errThing);
        errThing = 0;
    }
}
示例#22
0
bool JAMediaPlayer::on_bus_message(const Glib::RefPtr<Gst::Bus>& bus,
    const Glib::RefPtr<Gst::Message>& message){

    switch(message->get_message_type()){
        case Gst::MESSAGE_ELEMENT: {
            if (message->get_structure().has_name("prepare-xwindow-id")){
                Glib::RefPtr<Gst::Element> element =
                    Glib::RefPtr<Gst::Element>::cast_dynamic(message->get_source());
                Glib::RefPtr< Gst::ElementInterfaced<Gst::XOverlay> > xoverlay =
                    Gst::Interface::cast <Gst::XOverlay>(element);
                if (xoverlay){
                    xoverlay->set_xwindow_id(xid);}}
            break;}

        case Gst::MESSAGE_STATE_CHANGED:{
            Glib::RefPtr<Gst::MessageStateChanged> stateChangeMsg =
                Glib::RefPtr<Gst::MessageStateChanged>::cast_dynamic(message);
            if (stateChangeMsg){
                Gst::State oldState, newState, pendingState;
                stateChangeMsg->parse(oldState, newState, pendingState);
                if (estado != newState){
                    estado = newState;
                    if (estado == Gst::STATE_PLAYING){
                        signal_estado_update.emit("playing");
                        new_handler(true);}
                    else {signal_estado_update.emit("paused");
                        new_handler(false);}}}
            break;}

        case Gst::MESSAGE_EOS:{
            new_handler(false);
            signal_end.emit();
            return false;
            break;}

        case Gst::MESSAGE_ERROR:{
            Glib::RefPtr<Gst::MessageError> msgError =
                Glib::RefPtr<Gst::MessageError>::cast_static(message);
            if(msgError){
                Glib::Error err;
                err = msgError->parse();
                std::cerr << "Player Error: " << err.what() << std::endl;}
            else{
                std::cerr << "Player Error." << std::endl;}
            new_handler(false);
            return false;
            break;}

        case Gst::MESSAGE_TAG:{
            Glib::RefPtr<Gst::MessageTag> msg =
                Glib::RefPtr<Gst::MessageTag>::cast_static(message);
            Glib::ustring info = msg->get_structure().to_string();
            size_t found = info.find("video-codec");
            if (found!=std::string::npos){
                signal_video.emit();}
            signal_info_update.emit(info);
            break;}

        //elif message.type == gst.MESSAGE_BUFFERING:
        //    buf = int(message.structure["buffer-percent"])
        //    if buf < 100 and self.estado == gst.STATE_PLAYING:
        //        self.emit("loading-buffer", buf)
        //        self.__pause()
        //    elif buf > 99 and self.estado != gst.STATE_PLAYING:
        //        self.emit("loading-buffer", buf)
        //        self.play()

    }return true;}
CombineInstrumentsDialog::CombineInstrumentsDialog(Gtk::Window& parent, gig::File* gig)
    : ManagedDialog(_("Combine Instruments"), parent, true),
      m_gig(gig), m_fileWasChanged(false), m_newCombinedInstrument(NULL),
      m_cancelButton(_("_Cancel"), true), m_OKButton(_("_OK"), true),
      m_descriptionLabel(), m_tableDimCombo(2, 2), m_comboDimType(),
      m_labelDimType(Glib::ustring(_("Combine by Dimension:")) + "  ", Gtk::ALIGN_END)
{
    m_scrolledWindow.add(m_treeView);
    m_scrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);

    get_vbox()->pack_start(m_descriptionLabel, Gtk::PACK_SHRINK);
    get_vbox()->pack_start(m_tableDimCombo, Gtk::PACK_SHRINK);
    get_vbox()->pack_start(m_scrolledWindow);
    get_vbox()->pack_start(m_buttonBox, Gtk::PACK_SHRINK);

#if GTKMM_MAJOR_VERSION >= 3
    m_descriptionLabel.set_line_wrap();
#endif
    m_descriptionLabel.set_text(_(
        "Select at least two instruments below that shall be combined (as "
        "separate dimension zones of the selected dimension type) as a new "
        "instrument. The original instruments remain untouched.\n\n"
        "You may use this tool for example to combine solo instruments into "
        "a combi sound arrangement by selecting the 'layer' dimension, or you "
        "might combine similar sounding solo sounds into separate velocity "
        "split layers by using the 'velocity' dimension, and so on."
    ));

    // add dimension type combo box
    {
        int iLayerDimIndex = -1;
        Glib::RefPtr<Gtk::ListStore> refComboModel = Gtk::ListStore::create(m_comboDimsModel);
        for (int i = 0x01, iRow = 0; i < 0xff; i++) {
            Glib::ustring sType =
                dimTypeAsString(static_cast<gig::dimension_t>(i));
            if (sType.find("Unknown") != 0) {
                Gtk::TreeModel::Row row = *(refComboModel->append());
                row[m_comboDimsModel.m_type_id]   = i;
                row[m_comboDimsModel.m_type_name] = sType;
                if (i == gig::dimension_layer) iLayerDimIndex = iRow;
                iRow++;
            }
        }
        m_comboDimType.set_model(refComboModel);
        m_comboDimType.pack_start(m_comboDimsModel.m_type_id);
        m_comboDimType.pack_start(m_comboDimsModel.m_type_name);
        m_tableDimCombo.attach(m_labelDimType, 0, 1, 0, 1);
        m_tableDimCombo.attach(m_comboDimType, 1, 2, 0, 1);
        m_comboDimType.set_active(iLayerDimIndex); // preselect "layer" dimension
    }

    m_refTreeModel = Gtk::ListStore::create(m_columns);
    m_treeView.set_model(m_refTreeModel);
    m_treeView.set_tooltip_text(_(
        "Use SHIFT + left click or CTRL + left click to select the instruments "
        "you want to combine."
    ));
    m_treeView.append_column("Instrument", m_columns.m_col_name);
    m_treeView.set_headers_visible(false);
    m_treeView.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
    m_treeView.get_selection()->signal_changed().connect(
        sigc::mem_fun(*this, &CombineInstrumentsDialog::onSelectionChanged)
    );
    m_treeView.show();

    for (int i = 0; true; ++i) {
        gig::Instrument* instr = gig->GetInstrument(i);
        if (!instr) break;

#if DEBUG_COMBINE_INSTRUMENTS
        {
            std::cout << "Instrument (" << i << ") '" << instr->pInfo->Name << "' Regions: " << std::flush;
            for (gig::Region* rgn = instr->GetFirstRegion(); rgn; rgn = instr->GetNextRegion()) {
                std::cout << rgn->KeyRange.low << ".." << rgn->KeyRange.high << ", " << std::flush;
            }
            std::cout << std::endl;
        }
        std::cout << std::endl;
#endif
        
        Glib::ustring name(gig_to_utf8(instr->pInfo->Name));
        Gtk::TreeModel::iterator iter = m_refTreeModel->append();
        Gtk::TreeModel::Row row = *iter;
        row[m_columns.m_col_name] = name;
        row[m_columns.m_col_instr] = instr;
    }

    m_buttonBox.set_layout(Gtk::BUTTONBOX_END);
    m_buttonBox.set_border_width(5);
    m_buttonBox.pack_start(m_cancelButton, Gtk::PACK_SHRINK);
    m_buttonBox.pack_start(m_OKButton, Gtk::PACK_SHRINK);
    m_buttonBox.show();

    m_cancelButton.show();
    m_OKButton.set_sensitive(false);
    m_OKButton.show();

    m_cancelButton.signal_clicked().connect(
        sigc::mem_fun(*this, &CombineInstrumentsDialog::hide)
    );

    m_OKButton.signal_clicked().connect(
        sigc::mem_fun(*this, &CombineInstrumentsDialog::combineSelectedInstruments)
    );

    show_all_children();

    // show a warning to user if he uses a .gig in v2 format
    if (gig->pVersion->major < 3) {
        Glib::ustring txt = _(
            "You are currently using a .gig file in old v2 format. The current "
            "combine algorithm will most probably fail trying to combine "
            "instruments in this old format. So better save the file in new v3 "
            "format before trying to combine your instruments."
        );
        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_WARNING);
        msg.run();
    }
}
示例#24
0
bool Document::readPDF ()
{
	if (filename_.empty()) {
		DEBUG ("Document::readPDF: has no filename");
		return false;
	}

	std::string contentType = Gio::File::create_for_uri(filename_)->query_info("standard::content-type")->get_content_type();
	if (contentType != "application/pdf")
		return false;

	GError *error = NULL;
	PopplerDocument *popplerdoc = poppler_document_new_from_file (filename_.c_str(), NULL, &error);
	if (popplerdoc == NULL) {
		DEBUG ("Document::readPDF: Failed to load '%1'", filename_);
		g_error_free (error);
		return false;
	}

	Glib::ustring textdump;
	int num_pages = poppler_document_get_n_pages (popplerdoc);
	bool got_id = false;

	if (num_pages == 0) {
		DEBUG ("Document::readPDF: No pages in '%1'", filename_);
		return false;
	}

	// Read the first page
	PopplerPage *page;
	page = poppler_document_get_page (popplerdoc, 0);
	textdump += poppler_page_get_text(page);
	g_object_unref (page);

	// When we read the first page, see if it has the doc info
	bib_.guessYear (textdump);
	bib_.guessDoi (textdump);
	bib_.guessArxiv (textdump);

	if (!bib_.getDoi ().empty () || !bib_.getExtras ()["eprint"].empty ()) {
		got_id = true;
	}

	//Try to extract PDF metadata
	char *pdfauthor_c = poppler_document_get_author(popplerdoc);
	if (pdfauthor_c) {
		Glib::ustring pdfauthor = pdfauthor_c;
		if (pdfauthor != "" && pdfauthor.find(" ") != -1) {
			//If author contains more than one word, it might be sensible
			//Some bad examples: "Author", "jol", "IEEE",
			//"U-STAR\bgogul,S-1-5-21-2879401181-1713613690-3240760954-1005"
			
			bib_.setAuthors(pdfauthor);
		}
		DEBUG ("pdfauthor: %1", pdfauthor);
	}

	char *pdftitle_c = poppler_document_get_title(popplerdoc);
	if (pdftitle_c) {
		Glib::ustring pdftitle = pdftitle_c;
		if (pdftitle != "" && pdftitle.find(" ") != -1) {
			//If title contains more than one word, it might be sensible
			//Some bad examples: "Title", "ssl-attacks.dvi",
			//"doi:10.1016/j.scico.2005.02.009", "MAIN", "24690003",
			//"untitled", "PII: 0304-3975(96)00072-2"
			
			bib_.setTitle(pdftitle);
		}
		DEBUG ("pdftitle: %1", pdftitle);
	}
	

	g_object_unref (popplerdoc);

	//DEBUG ("%1", textdump);
	return !(textdump.empty ());
}