I'm working in a app with Gtk+2 and i need to implement a File treeview.
the actual code it's:
public FileTree() {
store = new TreeStore(2,typeof(string),typeof(string));
this.change_dir( "/dir/path" );
set_model( store );
// File icon
var pixbuf = new Gtk.CellRendererPixbuf();
var column = new Gtk.TreeViewColumn();
column.set_title("");
column.pack_start(pixbuf, false);
column.add_attribute(pixbuf,"stock-id",0);
column.set_alignment(1.0f);
append_column (column);
// File name
Gtk.CellRenderer cell = new Gtk.CellRendererText();
insert_column_with_attributes(-1,"", cell, "text", 1);
// Do some visual configs
this.config();
}
and change_dir():
public void change_dir( string path ) {
File repo_dir = File.new_for_path( path );
try {
generate_list( repo_dir, null, new Cancellable());
} catch ( Error e ) {
stderr.printf("Error: %s\n", e.message);
}
}
public void generate_list (
File file,
TreeIter? parent = null,
Cancellable? cancellable = null
) throws Error {
// Enumerator
FileEnumerator enumerator = file.enumerate_children (
"standard::*",
FileQueryInfoFlags.NOFOLLOW_SYMLINKS,
cancellable
);
FileInfo info = null;
TreeIter iter;
while(cancellable.is_cancelled() == false && ((info = enumerator.next_file(cancellable)) != null ))
{
// Check if not it's in the omited files.
if( ! (info.get_name() in IGNORED ) ) {
// Check if is a dir or a file
if( info.get_file_type() == FileType.DIRECTORY ) {
this.store.append( out iter, parent);
this.store.set(iter, 0, STOCK_DIRECTORY, 1, info.get_name());
File subdir = file.resolve_relative_path(info.get_name());
this.generate_list(subdir, iter, cancellable );
} else {
// It's a file
this.store.append( out iter, parent);
this.store.set(iter, 0, STOCK_FILE, 1, info.get_name());
}
}
}
if ( cancellable.is_cancelled()) {
throw new IOError.CANCELLED ("Operation was cancelled");
}
}
This it's showing two columns in ( first with a folder/file icon and the second one the name of the folder/file)
it's some way to do this in one single column??
EDIT: it could be some hack to set the icon at the side of the name, the actual code shows the icon and the string but when i expand a column, the strings moves a little to the right and there's a blank space between the icon and string.
With the method of the TreeViewColumn, pack_start(), I Just append any cell renderer to the column.
(in C this is like http://developer.gnome.org/gtk/unstable/gtk-question-index.html (see 5.3))
so, just modified:
// File icon
var pixbuf = new Gtk.CellRendererPixbuf();
var column = new Gtk.TreeViewColumn();
column.set_title("");
column.pack_start(pixbuf, false);
column.add_attribute(pixbuf,"stock-id",0);
column.set_alignment(1.0f);
append_column (column);
// File name
Gtk.CellRenderer cell = new Gtk.CellRendererText();
insert_column_with_attributes(-1,"", cell, "text", 1);
with:
// File icon
var pixbuf = new Gtk.CellRendererPixbuf();
column.set_title("");
column.pack_start(pixbuf, false);
column.add_attribute(pixbuf,"stock-id",0);
// The name of the file.
var cell = new Gtk.CellRendererText();
column.pack_start(cell, false);
column.add_attribute(cell,"text",1);
append_column (column);
And there it is :)
Related
How to determine whether a list is bulleted or numbered? I use OpenXML
In general, what will be the list determines NumberingDefinitionsPart, I thought to find out the Numbering of a certain element, but this method did not work
I am processing the list in the recommended way, but I need to know which way it is
`public void ParagraphHandle(Elements.Paragraph paragraph, StringBuilder text)
{
var docPart = paragraph.DocumentPart;
var element = paragraph.Element;
var r = element.Descendants<Numbering>().ToArray();
var images = GetImages(docPart, element);
if (images.Count > 0)
{
foreach (var image in images)
{
if (image.Id != null)
{
string filePath = _saveResources.SaveImage(image);
_handler.ImageHandle(filePath, text);
}
}
return;
}
var paragraphProperties = element.GetFirstChild<ParagraphProperties>();
var numberingProperties = paragraphProperties?.GetFirstChild<NumberingProperties>();
if (numberingProperties != null)
{
var numberingId = numberingProperties.GetFirstChild<NumberingId>()?.Val?.Value;
if (numberingId != null && !paragraph.IsList)
{
text.AppendLine("<ul>");
paragraph.IsList = true;
paragraph.List = new List();
_htmlGenerator.GenerateList(paragraph, text);
}
else
{
_htmlGenerator.GenerateList(paragraph, text);
}
}
else
{
if (paragraph.IsList)
{
text.AppendLine("</ul>");
paragraph.IsList = false;
}
_handler.ParagraphHandle(element, text);
}
}`
I have a Rectange in template file PPTX and setting name ="Img"
I want set image to that Rectange:
This is my code, but i can't call shape.Append(part);:
// Open the source document as read/write.
using (var presentationDocument = PresentationDocument.Open(strFile, true))
{
var presentationPart = presentationDocument.PresentationPart;
var templatePart = GetSlidePartsInOrder( presentationPart).Last();
for(int i = 0; i < 2; i++)
{
int ifile = i + 1;
string path = #"F:\AUTOM\t"+ ifile+".png";
var newSlidePart = CloneSlide(templatePart);
// Get the shape tree that contains the shape to change.
P.ShapeTree tree = newSlidePart.Slide.CommonSlideData.ShapeTree;
var shapes = from shape in newSlidePart.Slide.Descendants < P.Shape>()
select shape;
foreach (var shape in shapes)
{
if(shape.OuterXml.Contains("name=\"Img\""))
{
var part = newSlidePart.AddImagePart(ImageExtension(path));
using (var stream = File.OpenRead(path))
{
part.FeedData(stream);
}
**//shape.Append(part);**
}
else
{
// Specify the text of the title shape.
foreach (Paragraph paragraph in shape.Descendants().OfType<Paragraph>())
{
foreach (Run run in paragraph.Elements<Run>())
{
run.Text = new Text("Your new text");
}
}
}
}
AppendSlide(presentationPart, newSlidePart);
}
// Save the modified presentation.
presentationPart.Presentation.Save();
DeleteTemplateSlide(presentationDocument);
}
How set image to a Rectangle by OpenXML?
Greetings to all of you.
My problem is:
I need to search through user selected folder that contains MP3 files and check which file(s) has or contains specified tag. If it does, i will copy it to specified folder. I have managed to do something, but only partially, cause for example, i manage to copy genre "Pop" files, but not "Blues" files.
Getting contains to work is a total nightmare, cant get it to work at all.
Code:
try
{
FolderBrowserDialog folder = new FolderBrowserDialog();
DialogResult result = folder.ShowDialog();
string genre = "Blues";
var matchingFiles = Directory.GetFiles(folder.SelectedPath, "*.mp3", SearchOption.AllDirectories).Where(x =>
{
var f = TagLib.File.Create(x);
return (((TagLib.Id3v2.Tag)f.GetTag(TagTypes.Id3v2)).JoinedGenres == genre);
});
foreach (string f in matchingFiles)
{
System.IO.File.Copy(f, Path.Combine(#"destinationFolder", new FileInfo(f).Name));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Any help is welcome.
Problem solved:
try
{
FolderBrowserDialog folder = new FolderBrowserDialog();
DialogResult result = folder.ShowDialog();
string upit = search.Text;
var matchingFiles = Directory.GetFiles(folder.SelectedPath, "*.mp3", SearchOption.AllDirectories).Where(x =>
{
var f = TagLib.File.Create(x);
return (((TagLib.Id3v2.Tag)f.GetTag(TagTypes.Id3v2)).Comment != null && ((TagLib.Id3v2.Tag)f.GetTag(TagTypes.Id3v2)).Comment.Contains(upit));
}
);
foreach (string f in matchingFiles)
{
System.IO.File.Copy(f, Path.Combine(path, new FileInfo(f).Name));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n" + ex.StackTrace);
}
I want to highlight several keywords in a set of PDF files. Firstly, we have to identify the single words and match them with my keywords. I found an example:
class MyLocationTextExtractionStrategy : LocationTextExtractionStrategy
{
//Hold each coordinate
public List<RectAndText> myPoints = new List<RectAndText>();
List<string> topicTerms;
public MyLocationTextExtractionStrategy(List<string> topicTerms)
{
this.topicTerms = topicTerms;
}
//Automatically called for each chunk of text in the PDF
public override void RenderText(TextRenderInfo renderInfo)
{
base.RenderText(renderInfo);
//Get the bounding box for the chunk of text
var bottomLeft = renderInfo.GetDescentLine().GetStartPoint();
var topRight = renderInfo.GetAscentLine().GetEndPoint();
//Create a rectangle from it
var rect = new iTextSharp.text.Rectangle(
bottomLeft[Vector.I1],
bottomLeft[Vector.I2],
topRight[Vector.I1],
topRight[Vector.I2]
);
//Add this to our main collection
//filter the meaingless words
string text = renderInfo.GetText();
this.myPoints.Add(new RectAndText(rect, renderInfo.GetText()));
However, I found so many words are broken. For example, "stop" will be "st" and "op". Are there any other method to identify a single word and its position?
When you want to collect single words and their coordination, the better way is to override the existing LocationTextExtractionStrategy. Here is my code:
public virtual String GetResultantText(ITextChunkFilter chunkFilter){
if (DUMP_STATE) {
DumpState();
}
List<TextChunk> filteredTextChunks = filterTextChunks(locationalResult, chunkFilter);
filteredTextChunks.Sort();
List<RectAndText> tmpList = new List<RectAndText>();
StringBuilder sb = new StringBuilder();
TextChunk lastChunk = null;
foreach (TextChunk chunk in filteredTextChunks) {
if (lastChunk == null){
sb.Append(chunk.Text);
var startLocation = chunk.StartLocation;
var endLocation = chunk.EndLocation;
var rect = new iTextSharp.text.Rectangle(startLocation[0], startLocation[1], endLocation[0], endLocation[1]);
tmpList.Add(new RectAndText(rect, chunk.Text));
} else {
if (chunk.SameLine(lastChunk)){
// we only insert a blank space if the trailing character of the previous string wasn't a space, and the leading character of the current string isn't a space
if (IsChunkAtWordBoundary(chunk, lastChunk) && !StartsWithSpace(chunk.Text) && !EndsWithSpace(lastChunk.Text))
{
sb.Append(' ');
if (tmpList.Count > 0)
{
mergeAndStoreChunk(tmpList);
tmpList.Clear();
}
}
sb.Append(chunk.Text);
var startLocation = chunk.StartLocation;
var endLocation = chunk.EndLocation;
var rect = new iTextSharp.text.Rectangle(startLocation[0], startLocation[1], endLocation[0], endLocation[1]);
////var topRight = renderInfo.GetAscentLine().GetEndPoint();
tmpList.Add(new RectAndText(rect,chunk.Text));
} else {
sb.Append('\n');
sb.Append(chunk.Text);
}
}
lastChunk = chunk;
}
return sb.ToString();
}
private void mergeAndStoreChunk(List<RectAndText> tmpList)
{
RectAndText mergedChunk = tmpList[0];
int tmpListCount = tmpList.Count();
for (int i = 1; i < tmpListCount; i++)
{
RectAndText nowChunk = tmpList[i];
mergedChunk.Rect.Right = nowChunk.Rect.Right;
mergedChunk.Text += nowChunk.Text;
}
this.myPoints.Add(mergedChunk);
}
myPoints is a list, which will return all we want.
I need to transfer all the files dropped on an element to a server using HTML5 drag and drop.
I provided the corresponding js code below. I have a servlet in the server side to collect the files and put it in a folder. This is working fine if I drop 1 or 2 files on the page. But, if i drop 4-10 files, all the files are getting created in the server but multiple files are set to same content and some files content is 0K.
Can any of you please tell me how to achieve the correct behavior.
My requirement is similar to gmail attachments!!
Any solution which makes a sequential upload of files is much appreciable.
/*
* Upload files to the server using HTML 5 Drag and drop from the folders on your local computer
*/
function uploader(place, status, target, show) {
// Upload image files
upload = function(file) {
// Firefox 3.6, Chrome 6, WebKit
if(window.FileReader) {
// Once the process of reading file
this.loadEnd = function() {
bin = reader.result;
xhr = new XMLHttpRequest();
xhr.open('POST', target+'?up=true', false);
var body = bin;
xhr.setRequestHeader('content-type', 'multipart/form-data;');
xhr.setRequestHeader("file-name", file.name );
xhr.setRequestHeader("mime-type", file.type );
// Firefox 3.6 provides a feature sendAsBinary ()
if(xhr.sendAsBinary != null) {
xhr.sendAsBinary(body);
// Chrome 7 sends data but you must use the base64_decode on the PHP side
} else {
xhr.open('POST', target+'?up=true&base64=true', true);
xhr.setRequestHeader('UP-FILENAME', file.name);
xhr.setRequestHeader('UP-SIZE', file.size);
xhr.setRequestHeader('UP-TYPE', file.type);
xhr.send(window.btoa(bin));
}
if (show) {
var newFile = document.createElement('div');
newFile.innerHTML = 'Loaded : '+file.name+' size '+file.size+' B';
document.getElementById(show).appendChild(newFile);
}
if (status) {
document.getElementById(status).innerHTML = 'Loaded : 100%<br/>Next file ...';
}
};
// Loading errors
this.loadError = function(event) {
switch(event.target.error.code) {
case event.target.error.NOT_FOUND_ERR:
document.getElementById(status).innerHTML = 'File not found!';
break;
case event.target.error.NOT_READABLE_ERR:
document.getElementById(status).innerHTML = 'File not readable!';
break;
case event.target.error.ABORT_ERR:
break;
default:
document.getElementById(status).innerHTML = 'Read error.';
}
};
// Reading Progress
this.loadProgress = function(event) {
if (event.lengthComputable) {
var percentage = Math.round((event.loaded * 100) / event.total);
document.getElementById(status).innerHTML = 'Loaded : '+percentage+'%';
}
};
// Preview images
this.previewNow = function(event) {
bin = preview.result;
var img = document.createElement("img");
img.className = 'addedIMG';
img.file = file;
img.src = bin;
document.getElementById(show).appendChild(img);
};
reader = new FileReader();
// Firefox 3.6, WebKit
if(reader.addEventListener) {
reader.addEventListener('loadend', this.loadEnd, false);
if (status != null)
{
reader.addEventListener('error', this.loadError, false);
reader.addEventListener('progress', this.loadProgress, false);
}
// Chrome 7
} else {
reader.onloadend = this.loadEnd;
if (status != null)
{
reader.onerror = this.loadError;
reader.onprogress = this.loadProgress;
}
}
var preview = new FileReader();
// Firefox 3.6, WebKit
if(preview.addEventListener) {
preview.addEventListener('loadend', this.previewNow, false);
// Chrome 7
} else {
preview.onloadend = this.previewNow;
}
// The function that starts reading the file as a binary string
reader.readAsBinaryString(file);
// Preview uploaded files
if (show) {
preview.readAsDataURL(file);
}
// Safari 5 does not support FileReader
} else {
xhr = new XMLHttpRequest();
xhr.open('POST', target+'?up=true', true);
xhr.setRequestHeader('UP-FILENAME', file.name);
xhr.setRequestHeader('UP-SIZE', file.size);
xhr.setRequestHeader('UP-TYPE', file.type);
xhr.send(file);
if (status) {
document.getElementById(status).innerHTML = 'Loaded : 100%';
}
if (show) {
var newFile = document.createElement('div');
newFile.innerHTML = 'Loaded : '+file.name+' size '+file.size+' B';
document.getElementById(show).appendChild(newFile);
}
}
};
// Function drop file
this.drop = function(event) {
event.preventDefault();
var dt = event.dataTransfer;
var files = dt.files;
for (var i = 0; i<files.length; i++) {
var file = files[i];
upload(file);
}
};
// The inclusion of the event listeners (DragOver and drop)
this.uploadPlace = document.getElementById(place);
this.uploadPlace.addEventListener("dragover", function(event) {
event.stopPropagation();
event.preventDefault();
}, true);
this.uploadPlace.addEventListener("drop", this.drop, false);
}
Thank you.
I spent sometimes this morning in analyzing the same code from html5uploader. With some lucks, I found the root cause.
Change reader = new FileReader(); to var reader = new FileReader(); should solve the issue.
I bet this is because javascripts behaviour of auto-declaring undeclared variable as global variable. This caused the reader variable being reused by all the uploade(file) calls when more than one file is dropped to the browser.
Cheers!