private void Recognise() { if (inkCanvas.Strokes.Count == 0) { tbRecognised.Text = string.Empty; return; } using (MemoryStream ms = new MemoryStream()) { inkCanvas.Strokes.Save(ms); var ink = new Ink(); ink.Load(ms.ToArray()); using (RecognizerContext context = jpnRecognizer.CreateRecognizerContext()) { context.Strokes = ink.Strokes; var result = context.Recognize(out var status); if (status == RecognitionStatus.NoError) { tbRecognised.Text = result.TopString; } else { MessageBox.Show("Recognition failed"); } } } }
public string Recognize() { using (MemoryStream ms = new MemoryStream()) { // Build an inkCollector containing the strokes canvas.Strokes.Save(ms); var myInkCollector = new InkCollector(); var ink = new Ink(); ink.Load(ms.ToArray()); using (RecognizerContext context = recognizer.CreateRecognizerContext()) { RecognitionStatus status; context.Factoid = Factoid.WordList; // Magic smoke for name recognition context.Strokes = ink.Strokes; // Cannot do if there are no strokes if (ink.Strokes.Count > 0) { var results = context.Recognize(out status); if (status == RecognitionStatus.NoError) { return(results.ToString()); } } } } return(""); }
public ISpellComponent LoadComponent(UnLoadedSpellComponent spellUnLoaded) { string localPath = Path.Combine(path, spellUnLoaded.type.ToString()); localPath = Path.Combine(localPath, spellUnLoaded.name + ".json"); string json = File.ReadAllText(localPath); switch (spellUnLoaded.type) { case SpellComponent.SubSpellComponentType.Paper: SpellPage page = JsonUtility.FromJson <SpellPage>(json); return(page); case SpellComponent.SubSpellComponentType.Rune: SpellRune rune = JsonUtility.FromJson <SpellRune>(json); return(rune); case SpellComponent.SubSpellComponentType.language: Language lang = JsonUtility.FromJson <Language>(json); return(lang); case SpellComponent.SubSpellComponentType.Ink: Ink ink = JsonUtility.FromJson <Ink>(json); return(ink); default: return(null); } }
public void PostExport(Ink.Parsed.Story parsedStory, Ink.Runtime.Story runtimeStory) { var choiceJsonArray = new List<object> (); var allChoices = parsedStory.FindAll<Choice>(); foreach (Ink.Parsed.Choice choice in allChoices) { var sb = new StringBuilder (); if (choice.startContent != null) { sb.Append (choice.startContent.ToString ()); } if (choice.choiceOnlyContent) { sb.Append (choice.choiceOnlyContent.ToString ()); } // Note that this choice text is an approximation since // it can be dynamically generated at runtime. We are therefore // making the assumption that the startContent and choiceOnlyContent // lists contain only string value content. var choiceTextApproximation = sb.ToString (); var filename = choice.debugMetadata.fileName; var jsonObj = new Dictionary<string, object> (); jsonObj ["filename"] = filename; jsonObj ["choiceText"] = choiceTextApproximation; choiceJsonArray.Add (jsonObj); } var jsonString = choiceJsonArray.ToString (); File.WriteAllText ("choiceList.json", jsonString, System.Text.Encoding.UTF8); }
private void SaveGifButton_Clicked(object sender, RoutedEventArgs e) { if (inkCanvas.Strokes.Count <= 0) { return; } var dialog = new SaveFileDialog { Filter = "GIF files (*.gif)|*.gif", }; var ink = new Ink(); using (var stream = new MemoryStream()) { inkCanvas.Strokes.Save(stream); ink.Load(stream.ToArray()); } if (dialog.ShowDialog() == true) { using (var stream = new FileStream(dialog.FileName, FileMode.Create)) { var bytes = ink.Save(PersistenceFormat.Gif); stream.Write(bytes, 0, bytes.Length); } } }
public Ink MixColors(Ink inkA, Ink inkB) { float r = (inkA.color.r + inkB.color.r) / 2f; float g = (inkA.color.g + inkB.color.g) / 2f; float b = (inkA.color.b + inkB.color.b) / 2f; ColorMode cMode = ColorMode.NONE; if (inkA.colorMode == ColorMode.MAGENTA && inkB.colorMode == ColorMode.CYAN || inkA.colorMode == ColorMode.CYAN && inkB.colorMode == ColorMode.MAGENTA) { cMode = ColorMode.PURPLE; } else if (inkA.colorMode == ColorMode.MAGENTA && inkB.colorMode == ColorMode.YELLOW || inkA.colorMode == ColorMode.YELLOW && inkB.colorMode == ColorMode.MAGENTA) { cMode = ColorMode.ORANGE; } else if (inkA.colorMode == ColorMode.CYAN && inkB.colorMode == ColorMode.YELLOW || inkA.colorMode == ColorMode.YELLOW && inkB.colorMode == ColorMode.CYAN) { cMode = ColorMode.GREEN; } else { cMode = ColorMode.BLACK; } return(new Ink(new Color(r, g, b), cMode, 2)); }
public ActionResult InkAddEdit(Ink collection) { List <object> lst = new List <object>(); //Bind All the Data with the model lst.Add(collection.InkID); lst.Add(collection.InkType); lst.Add(collection.InkRemarks); object[] allitems = lst.ToArray(); if (collection.InkID == 0) // Add New Item { int output = ic.Database.ExecuteSqlCommand("insert into Inks(InkType,InkRemarks) values (@p1,@p2)", allitems); if (output > 0) { ViewBag.Itemmsg = "Ink Added Successfully"; } } else // Update existing { int output = ic.Database.ExecuteSqlCommand("Update Inks set InkType=@p1,InkRemarks=@p2 where InkID=@p0", allitems); if (output > 0) { ViewBag.Itemmsg = "Ink Updated Successfully"; } } return(View()); }
}//deleteLastStroke /// <summary> /// delete all the strokes on the basicOverlay /// </summary> internal void deleteAllStrokes() { if (basicOverlay.Ink.Strokes.Count == 1) { setFeedback("No ink to erase"); } else { // ask for confirmation -- should this be optional in gestureMode? DialogResult dr1 = System.Windows.Forms.MessageBox.Show( "Erase all ink on the overlay?", "PowerPoint", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation); if (dr1.Equals(DialogResult.OK)) // only proceed if OK button is pressed { // Get some information for undo first before deleting the strokes Ink cloneInk = basicOverlay.Ink.Clone(); // deep copy Strokes cloneStroke = cloneInk.Strokes; // a copy of strokes that will not be deleted undoStack.Push(""); undoStack.Push(""); undoStack.Push(cloneStroke); undoStack.Push("DeleteAllStrokes"); basicOverlay.Ink.DeleteStrokes(); Panel.Invalidate(); // repaints the window } setFeedback("Ink erased from overlay"); } }//deleteAllStrokes()
/// <summary> /// Deletes the last stroke added to the overlay /// </summary> /// <param name="undoable">whether to add the deleted stroke /// to the undo stack. True = add, false = do not add.</param> internal void deleteLastStroke(bool undoable) { int count = basicOverlay.Ink.Strokes.Count; if (count == 1) // that one count IS the leftdown stroke { setFeedback("No stroke to be deleted"); } else { setFeedback("Last stroke deleted"); Ink inkClone = basicOverlay.Ink.Clone(); // use for undo stroke basicOverlay.Ink.DeleteStroke(basicOverlay.Ink.Strokes[count - 2]); // delete the stroke before leftdown Panel.Invalidate(); // invalidate the window to repaint it // if we want this stroke to be undone, add its information to the undo stack if (undoable) { Strokes last = inkClone.Strokes; int numStroke = last.Count; for (int i = 0; i < numStroke - 2; i++) { last.RemoveAt(0); // remove everything except the last stroke, which is what we want } last.RemoveAt(1); // remove the gesture that triggered this undoStack.Push(""); undoStack.Push(""); undoStack.Push(last); // should only contain the last stroke now undoStack.Push("DeleteLastStroke"); } } }//deleteLastStroke
public void OnGridChanged(Ink ink, bool added) { if (ink == null) { return; } if (InkToNumberOfActiveInksOfThatType.ContainsKey(ink)) { if (added) { InkToNumberOfActiveInksOfThatType[ink] += 1; } else { InkToNumberOfActiveInksOfThatType[ink] += -1; } } else if (added) { InkToNumberOfActiveInksOfThatType.Add(ink, 1); } if (GridChanged != null) { GridChanged(); } }
private void RecognizeButton_Clicked(object sender, RoutedEventArgs e) { Candidates.Clear(); if (inkCanvas.Strokes.Count <= 0) { return; } using (var stream = new MemoryStream()) { inkCanvas.Strokes.Save(stream); var ink = new Ink(); ink.Load(stream.ToArray()); using (var context = new RecognizerContext()) { context.Strokes = ink.Strokes; var result = context.Recognize(out RecognitionStatus status); if (status == RecognitionStatus.NoError) { var candidates = result.GetAlternatesFromSelection(); foreach (var candidate in candidates) { Candidates.Add(candidate.ToString()); } } } } }
private void button1_Click(object sender, EventArgs e) { Ink ink = ic.Ink; string str = ic.Ink.Strokes.ToString(); textBox1.SelectedText = ic.Ink.Strokes.ToString(); }
/// <summary> /// Recognize ink data using the default recognizer. /// </summary> /// <returns>The string containing the top recognition result.</returns> protected String RecognizeInkData() { Debug.Assert(InkEnabled, null, "Client must be ink-enabled"); // Obtain the ink associated with this control Ink ink = inkOverlay.Ink; if (ink.Strokes.Count > 0) { // Attempt to create a recognition context and use it to // retrieve the top alternate. try { RecognizerContext recognizerContext = new RecognizerContext(); RecognitionStatus recognitionStatus; recognizerContext.Strokes = ink.Strokes; RecognitionResult recognitionResult = recognizerContext.Recognize(out recognitionStatus); if ((recognitionStatus == RecognitionStatus.NoError) && (null != recognitionResult)) { return(recognitionResult.TopString); } } catch (Exception) { // An exception will occur if the client does not have // any handwriting recognizers installed on their system. // In this case, we default to returning an empty string. } } return(String.Empty); }
/// <summary> /// 文字認識処理 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ButtonClick(object sender, RoutedEventArgs e) { using (var ms = new MemoryStream()) { theInkCanvas.Strokes.Save(ms); var myInkCollector = new InkCollector(); var ink = new Ink(); ink.Load(ms.ToArray()); using (var context = new RecognizerContext()) { if (ink.Strokes.Count > 0) { context.Strokes = ink.Strokes; RecognitionStatus status; var result = context.Recognize(out status); if (status == RecognitionStatus.NoError) { textBox1.Text = result.TopString; } else { MessageBox.Show("認識に失敗しました"); } } else { MessageBox.Show("文字が検出されませんでした"); } } } }
public string ToText(StrokeCollection strokes) { using (var ms = new MemoryStream()) { if (strokes == null) { return(null); } strokes.Save(ms); var ink = new Ink(); ink.Load(ms.ToArray()); if (ink.Strokes.Count <= 0) { return(null); } using (var context = new RecognizerContext()) { context.Strokes = ink.Strokes; var result = context.Recognize(out RecognitionStatus status); return(status == RecognitionStatus.NoError ? result.TopString : null); } } }
private static async void read(StorageFile file) { try { if (file != null) { if (Opened != null) { string value = await FileIO.ReadTextAsync(file); list.Clear(); XElement xml = XElement.Parse(value); if (xml.Name.LocalName == "drawing") { foreach (XElement element in xml.Descendants("ink")) { Ink ink = new Ink(); ink.Size = int.Parse(element.Attribute("size").Value); ink.Colour = stringToColour(element.Attribute("colour").Value); ink.Point = stringToPoint(element.Attribute("point").Value); list.Add(ink); } } Opened(list); } } } catch { } }
private void inkInput_StrokeCollected(object sender, InkCanvasStrokeCollectedEventArgs e) { if (inkInput.Strokes.Count == 0) { return; } MemoryStream ms = new MemoryStream(); inkInput.Strokes.Save(ms); InkCollector myInkCollector = new InkCollector(); Ink ink = new Ink(); ink.Load(ms.ToArray()); rct.StopBackgroundRecognition(); rct.Strokes = ink.Strokes; // rct.CharacterAutoCompletion = RecognizerCharacterAutoCompletionMode.Full; rct.BackgroundRecognizeWithAlternates(0); //timer.Start(); }
// Recognizes handwriting by using RecognizerContext private void buttonClick(object sender, RoutedEventArgs e) { using (MemoryStream ms = new MemoryStream()) { //theInkCanvas.Strokes.Save(ms); var myInkCollector = new InkCollector(); var ink = new Ink(); ink.Load(ms.ToArray()); using (RecognizerContext context = new RecognizerContext()) { if (ink.Strokes.Count > 0) { context.Strokes = ink.Strokes; RecognitionStatus status; var result = context.Recognize(out status); if (status == RecognitionStatus.NoError) { //textBox1.Text = result.TopString; //else MessageBox.Show("Recognition failed"); } } else { MessageBox.Show("No stroke detected"); } } } }
/// <summary> /// Converts the XML format into Ink strokes and creates a mapping between the XML stroke Ids and the /// Ink stroke Ids. /// </summary> public MakeInk(MakeXML xmlHolder, Ink ink) { this.ink = ink; this.idToCStroke = this.getIdToCStroke(xmlHolder.getSketch(), this.ink); calculateIdToMStroke(); this.idToMSubstrokes = new Hashtable(); }
public async Task<IActionResult> Edit(int id, [Bind("InkID,Title,Cost,Price,Quantity,Img")] Ink ink) { if (id != ink.InkID) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(ink); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!InkExists(ink.InkID)) { return NotFound(); } else { throw; } } return RedirectToAction("Index"); } return View(ink); }
void CreatInk(Vector3 posFinger, FingerGestures.Finger finger) { GameObject ink = Instantiate(inkPrefab) as GameObject; ink.transform.parent = LogicManager.LevelManager.GetLevelObject().transform; Vector3 pos = Camera.main.ScreenToWorldPoint(posFinger); pos.z = 0; ink.transform.position = pos; Ink inkCom = ink.GetComponent <Ink>(); if (inkDict.ContainsKey(finger.Index)) { if (inkDict[finger.Index] != null) { inkDict[finger.Index].Fade(); } inkDict[finger.Index] = inkCom; } else { inkDict.Add(finger.Index, inkCom); } }
private void addColor(MakeXML xmlHolder, Ink ink, Shape.ShapeType type) { Shape[] shapes = new Shape[0]; switch (type) { case (Shape.ShapeType.LABELED): shapes = xmlHolder.getSketch().Labeled; break; case (Shape.ShapeType.CLUSTERED): shapes = xmlHolder.getSketch().Clustered; break; } foreach (Shape shape in shapes) { string name = shape.Name; Color c = getRandomColor(); foreach (Shape.Arg arg in shape.Args) { string guid = arg.Id; Shape toColor = (Shape)xmlHolder.getSketch().IdToShape[guid]; if (toColor != null) { string guid2 = toColor.Id; if (guidToMStroke.ContainsKey(guid2)) { ((Microsoft.Ink.Stroke)guidToMStroke[guid2]).DrawingAttributes.Color = c; } } } } }
public bool InkPen(Pen pen, Ink ink) { var useCasePen = DtoToUseCaseDtoConverter.Convert(pen); var useCaseInk = DtoToUseCaseDtoConverter.Convert(ink); return(PenCollectorInteractor.InkPen(useCasePen, useCaseInk)); }
public async Task CreateInkAnnotation(PdfViewer pdfView) { var view = (pdfView.GetOrCreateRenderer() as PdfViewerRenderer)?.PdfDocView; if (view == null) { return; } // First, we define the bounding box of the annotation on the page. var boundingBox = new Rect(100, 100, 50, 75); // Now we specify which lines we want to draw. var lines = new List <IList <DrawingPoint> > { new List <DrawingPoint> { new DrawingPoint(100, 150), new DrawingPoint(125, 175), new DrawingPoint(150, 100) } }; // Create the annotation template var annotation = new Ink { BoundingBox = boundingBox, Lines = lines, LineWidth = 2, StrokeColor = Colors.Red, PageIndex = 0 }; // Add the annotation to the document in the view. await view.Document.CreateAnnotationAsync(annotation); }
InkParser(string str, string inkFilename = null, Ink.ErrorHandler externalErrorHandler = null, InkParser rootParser = null) : base(str) { _filename = inkFilename; RegisterExpressionOperators (); GenerateStatementLevelRules (); this.errorHandler = OnError; _externalErrorHandler = externalErrorHandler; if (rootParser == null) { _rootParser = this; _openFilenames = new HashSet<string> (); if (inkFilename != null) { var workingDir = Directory.GetCurrentDirectory(); var fullRootInkPath = Path.Combine (workingDir, inkFilename); _openFilenames.Add (fullRootInkPath); } } else { _rootParser = rootParser; } }
/// <summary> /// /// </summary> /// <param name="reader"></param> /// <param name="ink"></param> private Stroke handleStroke(XmlReader reader, Ink ink) { // new empty list to store the points List <Point> stroke = new List <Point>(); while (reader.Read()) { String nodeNameLowerCase = reader.Name.ToLower(); switch (nodeNameLowerCase) { case "p": // C# Seems to use Bankers' Rounding // Can we handle numbers like: x="2.80733975875E8" y="538.625" ??? YES, I think so... // Will we lose precision by casting to INT? int x = (int)Math.Round(Double.Parse(reader.GetAttribute("x"))); int y = (int)Math.Round(Double.Parse(reader.GetAttribute("y"))); //Console.WriteLine("Sample: {0} {1} {2} {3}", x, y, reader.GetAttribute("f"), reader.GetAttribute("t")); stroke.Add(new Point(x, y)); break; case "stroke": //Console.WriteLine("</Stroke>"); Point[] strokesArray = stroke.ToArray(); Stroke inkStroke = ink.CreateStroke(strokesArray); return(inkStroke); default: break; } } return(null); }
public void Start() { EnemyShoot shoot = this.GetComponent <EnemyShoot>(); NonMonoSpellGrid grid = new NonMonoSpellGrid(6, 6); Ink ink = ComponentLoader.GetInstance().LoadComponent(new ComponentLoader.UnLoadedSpellComponent("FireWeedSap", SpellComponent.SubSpellComponentType.Ink)) as Ink; grid.SetInk(ink); grid.SetPixel(2, 2, true); grid.SetPixel(2, 3, true); grid.SetPixel(3, 2, true); grid.SetPixel(3, 3, true); grid.SetPixel(4, 4, true); grid.SetPixel(3, 4, true); grid.SetPixel(4, 3, true); grid.SetPixel(2, 4, true); grid.SetPixel(4, 2, true); grid.SetPixel(3, 1, true); grid.SetPixel(3, 5, true); grid.SetPixel(1, 3, true); grid.SetPixel(5, 3, true); ProjectileSpellBookBuilder spellBuilder = new ProjectileSpellBookBuilder(ProjectileSpellBookBuilder.spellSource.enemy); spellBuilder.caster = gameObject; spellBuilder.grid = grid; spellBuilder.page = ComponentLoader.GetInstance().LoadComponent(new ComponentLoader.UnLoadedSpellComponent("Paper", SpellComponent.SubSpellComponentType.Paper)) as SpellPage; spellBuilder.lang = ComponentLoader.GetInstance().LoadComponent(new ComponentLoader.UnLoadedSpellComponent("English", SpellComponent.SubSpellComponentType.language)) as Language; spellBuilder.SetRune(ComponentLoader.GetInstance().LoadComponent(new ComponentLoader.UnLoadedSpellComponent("Raging Badger", SpellComponent.SubSpellComponentType.Rune)) as SpellRune); shoot.current_spell = spellBuilder.MakeSpellBook(); shoot.coolDown = spellBuilder.page.GetCoolDown(); }
public async Task <IActionResult> CloseOrder(int id, Order order) { if (order.OrderID != id) { return(NotFound()); } ApplicationUser user = await _userManager.GetUserAsync(User); var products = _context.CompositeProduct.Where(p => p.OrderID == id); ModelState.Remove("User"); if (ModelState.IsValid) { try { foreach (var product in products) { // update the qty of screenID and inkID if (product.ScreenID != null) { Screen screen = await _context.Screen.SingleOrDefaultAsync(s => s.ScreenID == product.ScreenID); screen.Quantity -= 1; Ink ink = await _context.Ink.SingleOrDefaultAsync(i => i.InkID == product.InkID); ink.Quantity -= 1; _context.Update(screen); _context.Update(ink); await _context.SaveChangesAsync(); } ProductType productType = await _context.ProductType.SingleOrDefaultAsync(p => p.ProductTypeID == product.ProductTypeID); productType.Quantity -= 1; _context.Update(productType); await _context.SaveChangesAsync(); } order.User = user; _context.Update(order); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!OrderExists(order.OrderID)) { return(NotFound()); } else { throw; } } return(RedirectToAction("Products", "Home")); } CloseOrderVM brokenModel = new CloseOrderVM(_context, (int)id, user); return(View(brokenModel)); }
/// <summary> /// Handle the reception of a RTStroke object. /// </summary> /// <param name="rtStroke">Stroke received</param> private void RTStrokeReceived(RTStroke rtStroke) { Page pg = rtDoc.Resources.Pages[rtStroke.PageIdentifier]; if (pg == null) // if the page is missing, ignore the stroke :( { return; } SizeF imageSize = GetSlideSize(pg.Image); // Resize the received stroke float xRatio = (imageSize.Width / constWidthPageSend) * inkSpaceToPixel; float yRatio = (imageSize.Height / constHeightPageSend) * inkSpaceToPixel; Rectangle bounds = rtStroke.Stroke.GetBoundingBox(); RectangleF newBounds = new RectangleF(bounds.X * xRatio, bounds.Y * yRatio, bounds.Width * xRatio, bounds.Height * yRatio); // Add the stroke to the page StringBuilder importData = new StringBuilder(2000); XmlTextWriter xml = CreateInitdXml(importData); xml.WriteStartElement("PlaceObjects"); xml.WriteAttributeString("pagePath", crntONFile); xml.WriteAttributeString("pageGuid", rtStroke.PageIdentifier.ToString("B")); xml.WriteStartElement("Object"); xml.WriteAttributeString("guid", rtStroke.StrokeIdentifier.ToString("B")); xml.WriteStartElement("Position"); xml.WriteAttributeString("x", newBounds.X.ToString()); xml.WriteAttributeString("y", newBounds.Y.ToString()); xml.WriteEndElement(); // end Position xml.WriteStartElement("Ink"); xml.WriteAttributeString("width", newBounds.Width.ToString()); xml.WriteAttributeString("height", newBounds.Height.ToString()); Ink ink = new Ink(); ink.AddStrokesAtRectangle(rtStroke.Strokes, rtStroke.Strokes.GetBoundingBox()); byte[] base64ISF_bytes = ink.Save(PersistenceFormat.Base64InkSerializedFormat); xml.WriteStartElement("Data"); xml.WriteBase64(base64ISF_bytes, 0, base64ISF_bytes.Length); xml.WriteEndElement(); // end Data xml.WriteEndDocument(); string finalData = importData.ToString(); LogAsLastCommand(finalData); importer.Import(finalData); // prevents ink & objects from getting inserted too quickly after a page System.Threading.Thread.Sleep(50); // Store the stroke ID in strokesPerPage ((ArrayList)strokesPerPage[rtStroke.PageIdentifier]).Add(rtStroke.StrokeIdentifier); }
protected RTStroke(SerializationInfo info, StreamingContext context) { ink = new Ink(); ink.Load((byte[])info.GetValue("Ink", typeof(byte[]))); DocumentIdentifier = new Guid(info.GetString("DocumentIdentifier")); PageIdentifier = new Guid(info.GetString("PageIdentifier")); Extension = info.GetValue("Extension", typeof(object)); }
public InkDetailPage(Ink ink) { InitializeComponent(); SelectedInk = ink; ManufacturerEntry.Text = SelectedInk.Manufacturer; ColourEntry.Text = SelectedInk.Colour; LabelDisplayName.Text = SelectedInk.DisplayName; }
/// <summary> /// Converts the XML format into Ink strokes and creates a mapping between the XML stroke Ids and the /// Ink stroke Ids. /// </summary> public MakeInk(MakeXML xmlHolder, Ink ink, Shape.ShapeType type) { this.ink = ink; this.idToCStroke = this.getIdToCStroke(xmlHolder.getSketch(), this.ink); calculateIdToMStroke(); this.idToMSubstrokes = new Hashtable(); addColor(xmlHolder, ink, type); }
public static Ink ToInk(this TraceGroup traceGroup) { var ink = new Ink(); foreach (var trace in traceGroup.Traces) { //var points = new Point[trace.Points.Count]; //foreach (var point in trace.Points) //{ //} var points = trace.Points.ToList().ConvertAll(c => c.ToPoint()); var stroke = ink.CreateStroke(points.ToArray()); ink.Strokes.Add(stroke); } return ink; }
public RTStroke(Guid documentIdentifier, Guid pageIdentifier, Stroke stroke, object extension ) { DocumentIdentifier = documentIdentifier; PageIdentifier = pageIdentifier; Extension = extension; if (! stroke.ExtendedProperties.DoesPropertyExist(ExtendedPropertyStrokeIdentifier)) { stroke.ExtendedProperties.Add(ExtendedPropertyStrokeIdentifier, Guid.NewGuid().ToString()); } int[] strokeIds = new int[1]; strokeIds[0] = stroke.Id; Strokes ourStroke = stroke.Ink.CreateStrokes(strokeIds); Ink fromInk = stroke.Ink; ink = fromInk.ExtractStrokes(ourStroke, ExtractFlags.CopyFromOriginal); }
/// <summary> /// Constructs a new <see cref="TouchGestureHandler"/> instance, which will /// keep track of the touch input and convert it into a gesture. /// </summary> public TouchGestureHandler(PresenterModel m, EventQueue q ) { this.model = m; this.currentDeckTraversal = null; // Listen for model changes this.eventQueue = q; this.currentDeckTraversalDispatcher = this.model.Workspace.CurrentDeckTraversal.ListenAndInitialize(this.eventQueue, delegate(Property<DeckTraversalModel>.EventArgs args) { this.currentDeckTraversal = args.New; }); // Keep track of the various touch strokes this.collectedPacketsTable = new Dictionary<int, List<int>>(); this.tabletPropertiesTable = new Dictionary<int, TabletPropertyDescriptionCollection>(); // Create a helper ink object this.ink = new Ink(); }
/// <summary> /// Create a Strokes object out of R3 Toolkit XML (superset of BNet XML) /// </summary> /// <param name="stream"></param> /// <returns></returns> public Strokes getStrokesFromXML(String xmlString) { // ink object for creating pen strokes InkCollector inkCollector = new InkCollector(); Ink ink = new Ink(); try { // object to parse the xml data StringReader stringReader = new StringReader(xmlString); XmlReader reader = XmlReader.Create(stringReader); // skip the junk nodes at the top of xml files reader.MoveToContent(); while (reader.Read()) { // read a tag String nodeNameLowerCase = reader.Name.ToLower(); switch (nodeNameLowerCase) { // name of the node case "stroke": // Console.WriteLine("<Stroke>"); Stroke stroke = handleStroke(reader, ink); //if (stroke != null) { // Console.WriteLine(stroke.GetPoints().Length + " points in this stroke."); //} break; default: break; } } } catch (XmlException xe) { Console.WriteLine("Recognizer encountered an exception in parsing the XML data. " + xe.Message); } // Console.WriteLine(ink.Strokes.Count + " total strokes."); return ink.Strokes; }
/// <summary> /// Listens to incoming messages and adds them to chat panel /// </summary> private void listenToIncomingMessages() { string message = null; string sErrorMessage = "Unknown"; // we are connected at this point this.Invoke(setStatusBarTextDelegate, new object[] {"Connection established."}); do { try { // reads in a single Base64 line of a single ink message = inputStream.ReadLine(); // see if connection was closed if (message == null) break; // create new incomingInk Ink incomingInk = new Ink(); // load data from base64 string incomingInk.Load(System.Text.Encoding.UTF8.GetBytes(message)); // add deserialized ink to chat window this.Invoke(addInkMessageDelegate,new object[] {incomingInk}); } catch (Exception ex) { sErrorMessage = ex.Message; break; } } while (message != null); // disable button this.Invoke(setStatusBarTextDelegate, new object[] {"Connection lost: " + sErrorMessage}); this.Invoke(setSendButtonStateDelegate, new object[] { false }); }
/// <summary> /// /// </summary> /// <param name="reader"></param> /// <param name="ink"></param> private Stroke handleStroke(XmlReader reader, Ink ink) { // new empty list to store the points List<Point> stroke = new List<Point>(); while (reader.Read()) { String nodeNameLowerCase = reader.Name.ToLower(); switch (nodeNameLowerCase) { case "p": // C# Seems to use Bankers' Rounding // Can we handle numbers like: x="2.80733975875E8" y="538.625" ??? YES, I think so... // Will we lose precision by casting to INT? int x = (int)Math.Round(Double.Parse(reader.GetAttribute("x"))); int y = (int)Math.Round(Double.Parse(reader.GetAttribute("y"))); //Console.WriteLine("Sample: {0} {1} {2} {3}", x, y, reader.GetAttribute("f"), reader.GetAttribute("t")); stroke.Add(new Point(x, y)); break; case "stroke": //Console.WriteLine("</Stroke>"); Point[] strokesArray = stroke.ToArray(); Stroke inkStroke = ink.CreateStroke(strokesArray); return inkStroke; default: break; } } return null; }
/*--------------------------------------------------------------------------------------*/ /*------------------------Event Handler for 'Open' Menu Item Click Event----------------*/ private void oPENToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog openDialogBox = new OpenFileDialog(); if (openDialogBox.ShowDialog() == System.Windows.Forms.DialogResult.OK) { FileInfo fileInfo = new FileInfo(openDialogBox.FileName); Byte[] b = new Byte[fileInfo.Length]; FileStream fileStream = new FileStream(openDialogBox.FileName, FileMode.Open); fileStream.Read(b, 0, b.Length); fileStream.Close(); Ink ink = new Ink(); ink.Load(b); drawingArea.InkEnabled = false; drawingArea.Ink = ink; drawingArea.InkEnabled = true; //RecognizeStroke(drawingArea); } }
/// <summary> /// Adds a single ink message to the main chat ink window /// </summary> /// <param name="ink">Ink to be added to the chat ink window</param> private void addInkMessage(Ink ink) { // calculate the bounds of the input and current chat panel Rectangle chatBounds = chatInkOverlay.Ink.GetBoundingBox(); Rectangle inputBounds = ink.GetBoundingBox(); int yPosition = chatBounds.Y + chatBounds.Height; // let's start drawing a little bit further down on the first ink if (yPosition == 0) yPosition = 20; try { // add strokes from the input message to the chat panel if (ink.Strokes.Count > 0) chatInkOverlay.Ink.AddStrokesAtRectangle(ink.Strokes, new Rectangle(inputBounds.X, yPosition,inputBounds.Width, inputBounds.Height)); // redraw chat panel redrawChatPanel(true); if (bSupportsTextRecognition) { try { // try recognizing string string sRecognizedString = ink.Strokes.ToString(); // append string if (sRecognizedString != string.Empty) recognizedString.Append(sRecognizedString + Environment.NewLine); } catch (Exception) { bSupportsTextRecognition = false; } } } catch (Exception ex) { this.Invoke(setStatusBarTextDelegate, new object[] { "Error: " + ex.Message }); } }
/// <summary> /// Helper class that is run on a different thread that converts the ink coordinates into pixel coordinates /// </summary> /// <param name="extracted">The strokes to convert and add to the model</param> private void HandleInkAddedHelper(Ink extracted) { // Adjust for differences in DPI if (ViewerStateModel.NonStandardDpi) { extracted.Strokes.Transform(ViewerStateModel.DpiNormalizationSendMatrix, true); } // Get the model object to add it to lock (WebService.Instance.GlobalModel) { SimpleWebDeck deck = (SimpleWebDeck)WebService.Instance.GlobalModel.Decks[WebService.Instance.GlobalModel.CurrentDeck]; SimpleWebSlide slide = (SimpleWebSlide)deck.Slides[WebService.Instance.GlobalModel.CurrentSlide - 1]; slide.Inks = new ArrayList(); // Extract each stroke foreach (Stroke s in extracted.Strokes) { // Get the points System.Drawing.Point[] pts = s.GetPoints(); // Convert and remove duplicates bool bFirst = true; ArrayList pts_new = new ArrayList(); System.Drawing.Point last = System.Drawing.Point.Empty; foreach (System.Drawing.Point p in pts) { System.Drawing.Point pNew = new System.Drawing.Point((int)Math.Round(p.X / 26.37f), (int)Math.Round(p.Y / 26.37f)); if (!bFirst && last == pNew) continue; bFirst = false; last = pNew; pts_new.Add(pNew); } // Add the points to the model SimpleWebInk stroke = new SimpleWebInk(); stroke.Pts = (System.Drawing.Point[])pts_new.ToArray(typeof(System.Drawing.Point)); stroke.R = s.DrawingAttributes.Color.R; stroke.G = s.DrawingAttributes.Color.G; stroke.B = s.DrawingAttributes.Color.B; stroke.Opacity = (s.DrawingAttributes.RasterOperation == RasterOperation.MaskPen) ? (byte)127 : (byte)255; stroke.Width = s.DrawingAttributes.Width / 26.37f; slide.Inks.Add(stroke); } } WebService.Instance.UpdateModel(); }
public void run() { System.Threading.Thread.CurrentThread.Priority = ThreadPriority.Highest; try { bool clientTalking = true; //a loop that reads from and writes to the socket while (clientTalking) { //get what client wants to say... byte[] bytes = new byte[8192]; // 8 KB de dados int bytesRec = this.socket.Receive(bytes); // System.Diagnostics.Debug.WriteLine("----- Recebido... -----"); ArrayList list = (ArrayList) getObjectWithByteArray(bytes); Object o = list[0]; String nomeEvento = (String) list[1]; // EVENTOS DO ARGO if (nomeEvento.Equals("PROT_atualiza_modelo_cliente")) { } if (nomeEvento.Equals("PROT_atualiza_modelo_cliente_inicial")) { ArrayList ListDoc = (ArrayList) o; // Global.main.OpenForCollaboration( ); Global.main.Invoke(new MainForm.DelegateOpenMetod(Global.main.OpenForCollaboration) ,new object[] { (TextWriter) ListDoc[0] }); } // Recebeu a notificação que algum cliente entrou na da sessão! if (nomeEvento.Equals("PROT_inicio_sessao")) { } // Recebeu a notificação que algum cliente saiu da sessão! if (nomeEvento.Equals("PROT_fim_sessao")) { } // Esta ação foi removida para a experiência /* if (nomeEvento.equals("ActionDeleteFromDiagram-actionPerformed")) ActionDeleteFromDiagram.SINGLETON.actionPerformedImpl((ActionEvent) o); */ // EVENTOS DO GEF // Desenho do TelePointer! #region mouseMovedPointer if (nomeEvento.Equals("mouseMovedPointer")) { /* // Sem os telePointers por enquanto ArrayList dados = (ArrayList) o; FigPointer fp = Global.main.fpA; String Id_tele = (String) dados[2]; if (Id_tele.Equals("1") ) fp = Global.main.fpA; if (Id_tele.Equals("2") ) fp = Global.main.fpB; if (Id_tele.Equals("3") ) fp = Global.main.fpC; if (Id_tele.Equals("4") ) fp = Global.main.fpD; fp.setCor((Color) dados[1] ); fp.setNome((String) dados[3]); fp.setLocation((Point) dados[0]); */ } #endregion #region inkoverlay_Stroke if (nomeEvento.Equals("inkoverlay_Stroke")) { ArrayList dados = (ArrayList) o; Ink x = new Ink(); x.Load( (byte[]) dados[0] ); Stroke s = x.Strokes[x.Strokes.Count-1]; // Testes: Adicionando a coleção de strokes! Global.main.doc.Ink.CreateStroke(s.GetPoints()); InkCollectorStrokeEventArgs e = new InkCollectorStrokeEventArgs(null ,s , false); // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateToMethod(Global.main.inkoverlay_StrokeImpl),new object[] { e }); } #endregion #region inkoverlay_StrokesDeleting if (nomeEvento.Equals("inkoverlay_StrokesDeleting")) { ArrayList dados = (ArrayList) o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateEraseMethod(Global.main.inkoverlay_StrokesDeletingImpl),new object[] { dados }); } #endregion #region inkoverlay_SelectionMovedOrResized if (nomeEvento.Equals("inkoverlay_SelectionMovedOrResized")) { ArrayList dados = (ArrayList) o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateEraseMethod(Global.main.inkoverlay_SelectionMovedOrResizedImpl),new object[] { dados }); } #endregion #region hover_EditCloneClicked if (nomeEvento.Equals("hover_EditCloneClicked")) { ArrayList dados = (ArrayList) o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateEraseMethod(Global.main.hover_EditCloneClickedImpl),new object[] { dados }); } #endregion #region hover_EditStraightenClicked if (nomeEvento.Equals("hover_EditStraightenClicked")) { ArrayList dados = (ArrayList) o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateEraseMethod(Global.main.hover_EditStraightenClickedImpl),new object[] { dados }); } #endregion #region hover_EditPropertiesClicked if (nomeEvento.Equals("hover_EditPropertiesClicked")) { ArrayList dados = (ArrayList) o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateEraseMethod(Global.main.hover_EditPropertiesClickedImpl),new object[] { dados }); } #endregion // Controles da simulação remota #region hover_AnimateClicked_Start if (nomeEvento.Equals("Start")) { // É preciso criar outra Thread aqui para continuar recebendo os dados.... // E depois é preciso terminá-la cr = new ClienteRecebe(this.socket); ThreadStart threadDelegate = new ThreadStart(cr.run); Thread tClienteRecebe = new Thread(threadDelegate); tClienteRecebe.Start(); Object dados = (Object) o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateSimulationMetod(Global.main.hover_AnimateClickedStartImpl),new object[] { dados }); /* tClienteRecebe.Abort(); Thread.Sleep(5); cr = null; */ } #endregion #region hover_AnimateClicked_Stop if (nomeEvento.Equals("Stop")) { Object dados = (Object) o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateSimulationMetod(Global.main.hover_AnimateClickedStopImpl),new object[] { dados }); // System.Threading.Thread.CurrentThread.Abort(); // É preciso cometer suicídio, ou seja, essa Thread deve se auto-terminar if(cr != null) return; } #endregion #region hover_AnimateClicked_Pause if (nomeEvento.Equals("Pause")) { Object dados = (Object) o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateSimulationMetod(Global.main.hover_AnimateClickedPauseImpl) ,new object[] { dados }); } #endregion #region hover_AnimateClicked_Resume if (nomeEvento.Equals("Resume")) { Object dados = (Object) o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateSimulationMetod(Global.main.hover_AnimateClickedResumeImpl) ,new object[] { dados }); } #endregion } } catch (ThreadAbortException e) { MessageBox.Show("ThreadAbortException in ClienteRecebe:" + e.Message , Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } catch (Exception e) { MessageBox.Show("Exception in ClienteRecebe:" + e.Message , Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
/// <summary> /// Ctor of ScaledInk class. /// </summary> /// <param name="pageInk">Ink of the page</param> /// <param name="pageWidth">Page width</param> /// <param name="pageHeight">Page height</param> public ScaledInk(Ink pageInk, float pageWidth, float pageHeight) { PageInk = pageInk; PageWidth = pageWidth; PageHeight = pageHeight; }
/// <summary> /// This method occurs when the form is loaded. It /// configures the insertion mode and the ink used by /// this application. /// </summary> /// <param name="sender">The control that raised the event.</param> /// <param name="e">The event arguments.</param> private void AutoClaims_Load(object sender, System.EventArgs e) { // Initialize the empty ink emptyInk = new Ink(); // Initialize the four different layers of ink on the vehicle diagram: // vehicle body, windows, tires, and headlights. inkLayers = new InkLayer[4]; inkLayers[0] = new InkLayer(new Ink(), Color.Red, false); inkLayers[1] = new InkLayer(new Ink(), Color.Violet, false); inkLayers[2] = new InkLayer(new Ink(), Color.LightGreen, false); inkLayers[3] = new InkLayer(new Ink(), Color.Aqua, false); // By default, select the first ink layer lstAnnotationLayer.SelectedIndex = 0; inkPictVehicle.DefaultDrawingAttributes.Color = inkLayers[lstAnnotationLayer.SelectedIndex].ActiveColor; // Currently there are recognizers that do not support regular expression // input scopes, thus raising exceptions. This try catch handler copes // with these differences in the recognizer. For policy numbers, nothing // is being done in reaction to this exception though since there is no // factoid that serves the same purpose. try { inkEdPolicyNumber.Factoid = "(0|1|2|3|4|5|6|7|8|9)(0|1|2|3|4|5|6|7|8|9)(0|1|2|3|4|5|6|7|8|9)-(0|1|2|3|4|5|6|7|" + "8|9)(0|1|2|3|4|5|6|7|8|9)(0|1|2|3|4|5|6|7|8|9)(0|1|2|3|4|5|6|7|8|9)"; } catch { // Do nothing } // There are also recognizers that do not support common input scopes as // well. This try catch handler copes with these differences in the // recognizer. For year, the NUMBER factoid is being set in reaction to // this exception. try { inkEdYear.Factoid = "(!IS_DATE_YEAR)"; } catch { inkEdYear.Factoid = Factoid.Number; } }
/// <summary> /// This method occurs when the form is loaded. It /// configures the insertion mode, the ink used by /// this application, and the default behavior for the PenInputPanels. /// </summary> /// <param name="sender">The control that raised the event.</param> /// <param name="e">The event arguments.</param> private void AutoClaims_Load(object sender, System.EventArgs e) { // Initialize the empty ink. emptyInk = new Ink(); // Create a list to store the Ink collected from the TIP. insertedInk = new System.Collections.Generic.List<Ink>(); // Create InkOverlay to display signature theInkOverlay = new InkOverlay(panelForSignature.Handle); theInkOverlay.Enabled = true; // Initialize the TextInputPanel objects inside a Try/Catch block // since the objects are not supported on some SKUs. try { // Initialize the TextInputPanel objects. // - tipShared is attached dynamically at run-time // - tipPolicyNumber is only attached to the Policy Number field // - tipName is only attached to the Insured Name field tipShared = new TextInputPanel(); tipPolicyNumber = new TextInputPanel(inkEdPolicyNumber); tipName = new TextInputPanel(inkEdName); tipSignature = new TextInputPanel(inkEdSignature); // Policy numbers are typically prone to recognizer errors, so we'll // default to the keyboard panel to be visible for the Policy number. // We set the PreferredInPlaceDirection to Top so that TIP does not cover the control below // We also set default inplace state to be expanded to save a step for the user. tipPolicyNumber.DefaultInputArea = PanelInputArea.Keyboard; tipPolicyNumber.PreferredInPlaceDirection = InPlaceDirection.Top; tipPolicyNumber.DefaultInPlaceState = InPlaceState.Expanded; // Policy name are also prone to recognizer error, so we'll default // to Character Pad. // We set the PreferredInPlaceDirection to Top so that TIP does not cover the control below // We also set default inplace state to be expanded. tipName.DefaultInputArea = PanelInputArea.WritingPad; tipName.PreferredInPlaceDirection = InPlaceDirection.Top; tipName.DefaultInPlaceState = InPlaceState.Expanded; // We default to lined input. We also default to opening TIP upward and expanded. tipSignature.DefaultInputArea = PanelInputArea.WritingPad; tipSignature.PreferredInPlaceDirection = InPlaceDirection.Top; tipSignature.DefaultInPlaceState = InPlaceState.Expanded; // Add Event Handlers for tipShared, so that we can track tipShared's events. tipShared.InputAreaChanging += new EventHandler<InputAreaChangeEventArgs>(tip_InputAreaChanging); tipShared.InputAreaChanged += new EventHandler<InputAreaChangeEventArgs>(tip_InputAreaChanged); tipShared.InPlaceVisibilityChanging += new EventHandler<InPlaceVisibilityChangeEventArgs>(tip_InPlaceVisibilityChanging); tipShared.InPlaceVisibilityChanged += new EventHandler<InPlaceVisibilityChangeEventArgs>(tip_InPlaceVisibilityChanged); tipShared.CorrectionModeChanging += new EventHandler<CorrectionModeChangeEventArgs>(tip_CorrectionModeChanging); tipShared.CorrectionModeChanged += new EventHandler<CorrectionModeChangeEventArgs>(tip_CorrectionModeChanged); tipShared.InPlaceSizeChanging += new EventHandler<InPlaceSizeChangeEventArgs>(tip_InPlaceSizeChanging); tipShared.InPlaceSizeChanged += new EventHandler<InPlaceSizeChangeEventArgs>(tip_InPlaceSizeChanged); tipShared.InPlaceStateChanging += new EventHandler<InPlaceStateChangeEventArgs>(tip_InPlaceStateChanging); tipShared.InPlaceStateChanged += new EventHandler<InPlaceStateChangeEventArgs>(tip_InPlaceStateChanged); tipShared.TextInserting += new EventHandler<TextInsertionEventArgs>(tip_TextInserting); tipShared.TextInserted += new EventHandler<TextInsertionEventArgs>(tip_TextInserted); // Add Event Handler for tipSignature, so that we can draw ink input on panelForDrawing. tipSignature.TextInserting += new EventHandler<TextInsertionEventArgs>(tip_TextInserting); tipSignature.TextInserted += new EventHandler<TextInsertionEventArgs>(tip_TextInserted); } catch (System.Runtime.InteropServices.COMException ex) { // If the peninputpanel objects cannot be created, set them // to null. Other code that references these objects will need // to check if (ex.ErrorCode == ObjectsNotInstalledError) { tipShared = null; tipPolicyNumber = null; tipName = null; } else { throw; // rethrow unexpected exception } } // Initialize the four different layers of ink on the vehicle diagram: // vehihcle body, windows, tires, and headlights. inkLayers = new InkLayer[4]; inkLayers[0] = new InkLayer(new Ink(), Color.Red, false); inkLayers[1] = new InkLayer(new Ink(), Color.Violet, false); inkLayers[2] = new InkLayer(new Ink(), Color.LightGreen, false); inkLayers[3] = new InkLayer(new Ink(), Color.Aqua, false); // By default, select the first ink layer lstAnnotationLayer.SelectedIndex = 0; inkPictVehicle.DefaultDrawingAttributes.Color = inkLayers[lstAnnotationLayer.SelectedIndex].ActiveColor; }
public InkParser(string str, string filenameForMetadata = null, Ink.ErrorHandler externalErrorHandler = null) : this(str, filenameForMetadata, externalErrorHandler, null) { }
/// <summary> /// Sends a single ink to the other client /// </summary> /// <param name="ink">Ink to be sent</param> private void sendInkMessage(Ink ink) { byte[] base64ISF_bytes; string base64ISF_string; if (outputStream != null) { #region serialize ink into base64 string // The following code snippet was taken from the Microsoft Tablet PC // Ink Serialization code example provided in the Table PC Developer SDK 1.5 // Get the base64 encoded ISF base64ISF_bytes = ink.Save(PersistenceFormat.Base64InkSerializedFormat); // Ink.Save returns a null terminated byte array. The encoding of the null // character generates a control sequence when it is UTF8 encoded. This // sequence is invalid in XML. Therefore, it is necessary to remove the // null character before UTF8 encoding the array. // The following loop finds the index of the first non-null byte in the byte // array returned by the Ink.Save method. int countOfBytesToConvertIntoString = base64ISF_bytes.Length - 1; for(; countOfBytesToConvertIntoString >= 0; --countOfBytesToConvertIntoString) { // Break the loop if the byte at the index is non-null. if(0 != base64ISF_bytes[countOfBytesToConvertIntoString]) break; } // Convert the index into count by incrementing it. countOfBytesToConvertIntoString++; // Convert it to a String base64ISF_string = System.Text.Encoding.UTF8.GetString(base64ISF_bytes, 0, countOfBytesToConvertIntoString); #endregion // send base64 string outputStream.WriteLine(base64ISF_string); } }
/// <summary> /// Constructs a new <see cref="Core"/> instance, which will /// render ink to the graphics device returned by the <see cref="SlideDisplayModel"/>. /// </summary> /// <remarks> /// Furthermore, the ink will be transformed using the /// <see cref="SlideDisplayModel.InkTransform"/> /// and clipped by <see cref="SlideDisplayModel.Bounds"/>. /// </remarks> public Core(SlideDisplayModel display) { this.m_SlideDisplay = display; this.m_Renderer = new Renderer(); this.m_Ink = new Ink(); this.m_DrawingAttributes = new DrawingAttributes(); this.m_PacketsTable = new Dictionary<int,int[]>(); this.m_DrawingAttributesTable = new Dictionary<int,DrawingAttributes>(); this.m_TabletPropertiesTable = new Dictionary<int,TabletPropertyDescriptionCollection>(); this.m_CollectedPacketsTable = new Dictionary<int, List<int>>(); this.m_CurrentStrokeIdTable = new Dictionary<int, int>(); this.m_SlideDisplay.Changed["InkTransform"].Add(new PropertyEventHandler(this.HandleInkTransformChanged)); this.HandleInkTransformChanged(display, null); }
private void LoadISF(Stream s) { Ink loadedInk = new Ink(); Byte[] isfBytes = new byte[s.Length]; if (s.Read(isfBytes, 0, isfBytes.Length) == s.Length) { loadedInk.Load(isfBytes); myInkCollector.Enabled = false; s.Close(); } myInkCollector.Ink = loadedInk; myInkCollector.Enabled = true; this.Invalidate(); }
public SerializedInk(Ink ink) { inkData = ink.Save(PersistenceFormat.InkSerializedFormat); }
private void HandleInkAddedHelper(Ink extracted, Group receivers) { if (ViewerStateModel.NonStandardDpi) { extracted.Strokes.Transform(ViewerStateModel.DpiNormalizationSendMatrix, true); } try { Message message = new InkSheetStrokesAddedMessage(this.m_Sheet, m_SlideID, this.SheetCollectionSelector, extracted); message.Group = receivers; message.Tags = new MessageTags(); message.Tags.SlideID = m_SlideID; message.Tags.BridgePriority = MessagePriority.Higher; this.Sender.Send(message); } catch (OutOfMemoryException e) { Trace.WriteLine(e.ToString()); GC.Collect(); } }
private void LoadInkIntoTarget(InkSheetModel sheet, byte[] saved, out int[] ids) { Ink restored = new Ink(); restored.Load(saved); using(Synchronizer.Lock(sheet.Ink.Strokes.SyncRoot)) { ids = new int[restored.Strokes.Count]; for(int i = 0; i < ids.Length; i++) { Stroke stroke = restored.Strokes[i]; // Remove any strokes that have the same remote Id as the new one. // Unfortunately, because the InkSheetUndoService cannot preserve stroke referential identity, // we must do a full search each time and cannot simply keep a table. if(stroke.ExtendedProperties.DoesPropertyExist(StrokeIdExtendedProperty)) { object id = stroke.ExtendedProperties[StrokeIdExtendedProperty].Data; foreach(Stroke existing in sheet.Ink.Strokes) { if(existing.ExtendedProperties.DoesPropertyExist(StrokeIdExtendedProperty)) { if(id.Equals(existing.ExtendedProperties[StrokeIdExtendedProperty].Data)) { StrokesEventArgs args = new StrokesEventArgs(new int[] { existing.Id }); sheet.OnInkDeleting(args); sheet.Ink.DeleteStroke(existing); sheet.OnInkDeleted(args); } } } } // The stroke has no association with the current Ink object. // Therefore, we have to recreate it by copying the raw packet data. // This first requires recreating the TabletPropertyDescriptionCollection, // which, for some stupid reason, must be done manually for lack of a better API. TabletPropertyDescriptionCollection properties = new TabletPropertyDescriptionCollection(); foreach(Guid property in stroke.PacketDescription) properties.Add(new TabletPropertyDescription(property, stroke.GetPacketDescriptionPropertyMetrics(property))); // Create a new stroke from the raw packet data. Stroke created = sheet.Ink.CreateStroke(stroke.GetPacketData(), properties); // Copy the DrawingAttributes and all application data // (especially the StrokesIdExtendedProperty) to the new stroke. created.DrawingAttributes = stroke.DrawingAttributes; foreach(ExtendedProperty prop in stroke.ExtendedProperties) created.ExtendedProperties.Add(prop.Id, prop.Data); ids[i] = created.Id; if (ViewerStateModel.NonStandardDpi) created.Transform(ViewerStateModel.DpiNormalizationReceiveMatrix); } } }
protected RTStroke(SerializationInfo info, StreamingContext context) { ink = new Ink(); ink.Load((byte[])info.GetValue("Ink", typeof(byte[]))); DocumentIdentifier = new Guid(info.GetString("DocumentIdentifier")); PageIdentifier = new Guid(info.GetString("PageIdentifier")); Extension = info.GetValue("Extension", typeof(object)); }
public InkSheetStrokesAddedMessage(InkSheetModel sheet, Guid slideId, SheetCollection selector, Ink ink) : base(sheet, selector) { this.SavedInks = new byte[][] { ink.Save() }; SlideId = slideId; }
private void HandleInkAddedHelper(Ink extracted) { Message message, deck, slide, sheet; message = new PresentationInformationMessage(this.Presentation); message.InsertChild(deck = new DeckInformationMessage(this.Deck)); deck.InsertChild(slide = new SlideInformationMessage( GetSubmissionSlideModel(), false )); slide.InsertChild(sheet = new InkSheetStrokesAddedMessage(this.m_Sheet, (Guid)slide.TargetId, this.SheetCollectionSelector, extracted)); sheet.AddOldestPredecessor( SheetMessage.RemoteForSheet( this.m_Sheet, this.SheetCollectionSelector ) ); this.Sender.Send(message); }
/// <summary> /// Handle the reception of a RTStroke object. /// </summary> /// <param name="rtStroke">Stroke received</param> private void RTStrokeReceived(RTStroke rtStroke) { Page pg = rtDoc.Resources.Pages[rtStroke.PageIdentifier]; if( pg == null ) // if the page is missing, ignore the stroke :( return; SizeF imageSize = GetSlideSize( pg.Image ); // Resize the received stroke float xRatio = (imageSize.Width / constWidthPageSend)*inkSpaceToPixel; float yRatio = (imageSize.Height / constHeightPageSend)*inkSpaceToPixel; Rectangle bounds = rtStroke.Stroke.GetBoundingBox(); RectangleF newBounds = new RectangleF( bounds.X*xRatio, bounds.Y*yRatio, bounds.Width*xRatio, bounds.Height*yRatio ); // Add the stroke to the page StringBuilder importData = new StringBuilder(2000); XmlTextWriter xml = CreateInitdXml(importData); xml.WriteStartElement( "PlaceObjects" ); xml.WriteAttributeString( "pagePath", crntONFile ); xml.WriteAttributeString( "pageGuid", rtStroke.PageIdentifier.ToString("B") ); xml.WriteStartElement( "Object" ); xml.WriteAttributeString( "guid", rtStroke.StrokeIdentifier.ToString("B") ); xml.WriteStartElement( "Position" ); xml.WriteAttributeString( "x", newBounds.X.ToString() ); xml.WriteAttributeString( "y", newBounds.Y.ToString() ); xml.WriteEndElement(); // end Position xml.WriteStartElement( "Ink" ); xml.WriteAttributeString( "width", newBounds.Width.ToString() ); xml.WriteAttributeString( "height", newBounds.Height.ToString() ); Ink ink = new Ink(); ink.AddStrokesAtRectangle( rtStroke.Strokes, rtStroke.Strokes.GetBoundingBox() ); byte[] base64ISF_bytes = ink.Save( PersistenceFormat.Base64InkSerializedFormat ); xml.WriteStartElement( "Data" ); xml.WriteBase64( base64ISF_bytes, 0, base64ISF_bytes.Length ); xml.WriteEndElement(); // end Data xml.WriteEndDocument(); string finalData = importData.ToString(); LogAsLastCommand( finalData ); importer.Import( finalData ); // prevents ink & objects from getting inserted too quickly after a page System.Threading.Thread.Sleep(50); // Store the stroke ID in strokesPerPage ((ArrayList)strokesPerPage[rtStroke.PageIdentifier]).Add(rtStroke.StrokeIdentifier); }
/// <summary> /// Event Handler from Form Load Event /// Set up the real time stylus for collection /// </summary> /// <param name="sender">The control that raised the event.</param> /// <param name="e">The event arguments.</param> private void InkCollection_Load(object sender, System.EventArgs e) { // Create the renderers. The dynamic renderer is used to render the ink // stroke that is currently being collected, whereas the static renderer // is used to render strokes that have already been collected. myDynamicRenderer = new DynamicRenderer(this); myRenderer = new Renderer(); // // If you do not modify the default drawing attributes, the default // drawing attributes will use the following properties and values: // // AntiAliased = true // Color = black // FitToCurve = false // Height = 1 // IgnorePressure = false // PenTip = ball // RasterOperation = copy pen // Transparency = 0 // Width = 53 (2 pixels on a 96 dpi screen) // // For an example of how to modify other drawing attributes, uncomment // the following lines of code: // myDynamicRenderer.DrawingAttributes.PenTip = PenTip.Rectangle; // myDynamicRenderer.DrawingAttributes.Height = (.5F)*MediumInkWidth; // myDynamicRenderer.DrawingAttributes.Transparency = 128; // // Create the real time stylus used to receive stylus notifications myRealTimeStylus = new RealTimeStylus(this, true); // Add the dynamic renderer to the synchronous plugin notification chain. // Synchronous notifications occur on the pen thread. myRealTimeStylus.SyncPluginCollection.Add(myDynamicRenderer); // Add the form to the asynchronous plugin notification chain. This plugin // will be used to collect stylus data into an ink object. Asynchronous // notifications occur on the UI thread. myRealTimeStylus.AsyncPluginCollection.Add(this); // Enable the real time stylus and the dynamic renderer myRealTimeStylus.Enabled = true; myDynamicRenderer.Enabled = true; // Create the ink object used to store ink collected from the real time stylus myPackets = new Hashtable(); myInk = new Ink(); }
//Recognizes the stroke private void recogClick(object sender, EventArgs e) { if (inkCanvas.Strokes.Count > 0) { StrokeCollection strokeList = inkCanvas.Strokes; //save the strokes MemoryStream ms = new MemoryStream(); inkCanvas.Strokes.Save(ms); InkCollector collector = new InkCollector(); Ink ink = new Ink(); ink.Load(ms.ToArray()); try { context = new RecognizerContext(); RecognitionStatus status; RecognitionResult result; context.Strokes = ink.Strokes; result = context.Recognize(out status); if (result.TopString == levelStr) { resultStr = "WON"; resultSplash = new ResultSplashScreen(); resultSplash.Show(); Thread.Sleep(1000); resultSplash.Close(); MessageBoxResult diagRes = MessageBox.Show("Do you want to proceed?\nYes to Proceed\nNo to Try Again", "important", MessageBoxButton.YesNo, MessageBoxImage.Question); //Change theme, if colorblind and progress to new level if (diagRes == MessageBoxResult.Yes) { write.Hide(); //Create a method that says "solved" after each level on the button //xxxxxxxx if (isColorBlind == true) { write.updateLevelProgress(); write.newLevel(isColorBlind); write.saveLevelProgress(levelStr); } else { write.updateLevelProgress(); write.newLevel(isColorBlind); write.saveLevelProgress(levelStr); } } //Otherwise, repeat the level else if (diagRes == MessageBoxResult.No) { if (isColorBlind == true) { write.repeatLevel(isColorBlind); } else { write.repeatLevel(isColorBlind); } } } else { resultStr = "LOSE"; resultSplash = new ResultSplashScreen(); resultSplash.Show(); Thread.Sleep(1000); resultSplash.Close(); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } //Clear strokes after every try inkCanvas.Strokes.Clear(); } else { MessageBox.Show("Nothing"); } }
/// <summary> /// Constructor for InkLayer /// </summary> /// <param name="ink">The ink</param> /// <param name="color">The color of the layer</param> /// <param name="hidden">True if the layer is hidden</param> public InkLayer(Ink ink, Color color, bool hidden) { myInk = ink; myColor = color; myHidden = hidden; }
public static string ToString(Ink ink) { if (ink == null) return null; byte[] bits = ink.Save(PersistenceFormat.InkSerializedFormat,CompressionMode.Maximum); return System.Convert.ToBase64String(bits); }