/// <summary> /// Sends bytes. /// </summary> /// <param name="data">Byte array that contains data to send.</param> /// <param name="offset">Offset in data</param> /// <param name="length">Length of bytes to transmit</param> /// <param name="localEcho">Whether bytes can be repeated as local echo</param> private void TransmitInternal(byte[] data, int offset, int length, bool localEcho) { // Note: // This method may be called from multiple threads. // One is UI thread which is processing key events, and another is communication thread // which is going to send back something. // // Some IPoderosaSocket implementations have thread-safe Transmit() method, but not all. // So we transmit data exclusively. lock (_transmitSync) { try { if (localEcho && _settings.LocalEcho) { _dataForLocalEcho.Set(data, 0, data.Length); _host.OnReception(_dataForLocalEcho); } _connection.Socket.Transmit(data, offset, length); } catch (Exception) { try { _connection.Close(); } catch (Exception ex) { RuntimeUtil.ReportException(ex); } _host.TerminalHost.OwnerWindow.Warning(GEnv.Strings.GetString("Message.TerminalControl.FailedToSend")); } } }
private void OnOK(object sender, EventArgs args) { try { TypedHashtable <IShellScheme, IShellScheme> table = new TypedHashtable <IShellScheme, IShellScheme>(); List <IShellScheme> newscheme = new List <IShellScheme>(); IShellScheme newdefault = null; foreach (ItemTag tag in _tags) { if (tag.Original != null) { table.Add(tag.Original, tag.ShellScheme); } newscheme.Add(tag.ShellScheme); if (tag.ShellScheme.IsGeneric) { newdefault = tag.ShellScheme; } } foreach (ItemTag tag in _removing) { table.Add(tag.Original, newdefault); } _schemeCollection.UpdateAll(newscheme.ToArray(), table); } catch (Exception ex) { RuntimeUtil.ReportException(ex); } }
private static CommandResult SaveShortcutFile(ICommandTarget target) { ITerminalControlHost t = TerminalCommandTarget.AsTerminal(target); if (t == null) { return(CommandResult.Failed); } SaveFileDialog dlg = new SaveFileDialog(); dlg.Title = TEnv.Strings.GetString("Caption.SaveShortcutFile"); dlg.DefaultExt = "gts"; dlg.AddExtension = true; dlg.Filter = "Terminal Shortcut(*.gts)|*.gts"; if (dlg.ShowDialog() == DialogResult.OK) { try { new ShortcutFileContent(t.TerminalSettings, t.TerminalConnection.Destination).SaveToXML(dlg.FileName); return(CommandResult.Succeeded); } catch (Exception ex) { RuntimeUtil.ReportException(ex); return(CommandResult.Failed); } } else { return(CommandResult.Cancelled); } }
public bool Verify(ISSHLoginParameter param, SSHConnectionInfo info) { if (!_loaded) { try { Load(); } catch (Exception ex) { //ロード中のエラーのときは鍵は拒否。安全側に! RuntimeUtil.ReportException(ex); return(false); } } string keystr = info.DumpHostKeyInKnownHostsStyle(); string local = param.Method == SSHProtocol.SSH1 ? _dataForSSH1[ToKeyString(param)] : _dataForSSH2[ToKeyString(param)]; if (local == null) { return(AskUserReliability(param, info, keystr, "Message.HostKeyChecker.AskHostKeyRegister")); } else if (keystr != local) { return(AskUserReliability(param, info, keystr, "Message.HostKeyChecker.AskHostKeyRenew")); } else { return(true); } }
private void CreateFonts() { _font = new FontHandle(RuntimeUtil.CreateFont(_fontName, _fontSize), _useClearType); FontStyle fs = _font.Font.Style; _boldfont = new FontHandle(new Font(_font.Font, fs | FontStyle.Bold), _useClearType); _underlinefont = new FontHandle(new Font(_font.Font, fs | FontStyle.Underline), _useClearType); _boldunderlinefont = new FontHandle(new Font(_font.Font, fs | FontStyle.Underline | FontStyle.Bold), _useClearType); _cjkFont = new FontHandle(new Font(_cjkFontName, _fontSize), _useClearType); fs = _cjkFont.Font.Style; _cjkBoldfont = new FontHandle(new Font(_cjkFont.Font, fs | FontStyle.Bold), _useClearType); _cjkUnderlinefont = new FontHandle(new Font(_cjkFont.Font, fs | FontStyle.Underline), _useClearType); _cjkBoldUnderlinefont = new FontHandle(new Font(_cjkFont.Font, fs | FontStyle.Underline | FontStyle.Bold), _useClearType); _usingIdenticalFont = (_font.Font.Name == _cjkFont.Font.Name); //通常版 Graphics g = Graphics.FromHwnd(Win32.GetDesktopWindow()); IntPtr hdc = g.GetHdc(); Win32.SelectObject(hdc, _font.HFONT); Win32.SIZE charsize1, charsize2; Win32.GetTextExtentPoint32(hdc, "A", 1, out charsize1); Win32.GetTextExtentPoint32(hdc, "AAA", 3, out charsize2); _pitch = new SizeF((charsize2.width - charsize1.width) / 2, charsize1.height); _chargap = (charsize1.width - _pitch.Width) / 2; g.ReleaseHdc(hdc); g.Dispose(); }
public bool Verify(ISSHHostKeyInformationProvider info) { if (!_loaded) { try { Load(); } catch (Exception ex) { //ロード中のエラーのときは鍵は拒否。安全側に! RuntimeUtil.ReportException(ex); return(false); } } string keystr = info.KnownHostsString; string local = (info.Protocol == SSHProtocol.SSH1) ? _dataForSSH1[ToKeyString(info)] : _dataForSSH2[ToKeyString(info)]; if (local == null) { return(AskUserReliability(info, keystr, "Message.HostKeyChecker.AskHostKeyRegister")); } else if (keystr != local) { return(AskUserReliability(info, keystr, "Message.HostKeyChecker.AskHostKeyRenew")); } else { return(true); } }
internal MacroExecutor RunMacroModule(MacroModule module, ISession sessionToBind, IMacroEventListener listener) { try { Assembly asm = MacroUtil.LoadMacroAssembly(module); MacroExecutor macroExec = new MacroExecutor(module, asm); if (sessionToBind != null) { bool bound = _sessionBinder.Bind(macroExec, sessionToBind); if (!bound) { GUtil.Warning(null, Strings.GetString("Message.MacroPlugin.AnotherMacroIsRunningInThisSession")); return(null); } } if (listener != null) { listener.IndicateMacroStarted(); } macroExec.AsyncExec(listener); return(macroExec); } catch (Exception ex) { RuntimeUtil.ReportException(ex); return(null); } }
public int Execute(Frame frame) { object result = frame.result; if (to.IsAssignableFrom(result)) { return(1); } RedwoodType type; if (result is RedwoodObject rwo) { type = rwo.Type; } else { type = RedwoodType.GetForCSharpType(result.GetType()); } // TODO: this may be repeating existing work that occurs later if (!type.HasImplicitConversion(to)) { throw new NotImplementedException(); } Lambda conversion = RuntimeUtil.GetConversionLambda(type, to); frame.result = conversion.Run(frame.result); return(1); }
public void AsyncConnect() { bool success = false; _asyncThread = Thread.CurrentThread; try { ITerminalConnection result = Connect(); if (!_interrupted) { success = true; Debug.Assert(result != null); ProtocolUtil.FireConnectionSucceeded(_param); _client.SuccessfullyExit(result); } } catch (Exception ex) { if (!(ex is LocalShellUtilException)) { RuntimeUtil.ReportException(ex); } if (!_interrupted) { _client.ConnectionFailed(ex.Message); ProtocolUtil.FireConnectionFailure(_param, ex.Message); } } finally { if (!success && _process != null && !_process.HasExited) { _process.Kill(); } } }
private List <Type> GetMainComponentTypeNames() { var list = new List <Type>(); var typeMap = RuntimeUtil.GetAllTypesDerivedFrom <MainComponent>(); foreach (var kvp in typeMap) { var type = kvp; if (RuntimeUtil.HasSubclass(type)) { continue; } if (type.IsDefined(typeof(ComponentHandlerAttribute), false)) { var attribute = type.GetAttribute <ComponentHandlerAttribute>(); if (attribute != null && attribute.handler != null) { list.Add(type); } } else { list.Add(type); } } list.Sort((a, b) => { return(a.Name.CompareTo(b.Name)); }); return(list); }
private object GetValue(object o) { var source = FindSource(o); object value = null; if (string.IsNullOrEmpty(this.Path)) { //当没有指定path时,以源作为value value = source; } else { var dtoSource = source as DTObject; if (dtoSource != null) { value = dtoSource.GetValue(this.Path); } else { value = RuntimeUtil.GetPropertyValue(source, this.Path); } } if (this.Converter != null) { value = this.Converter.Convert(value, this.Parameter); } return(value); }
private void LoadInnerProperty(LoadContext ctx, object obj, string innerName, string attrValue) { var current = obj; var propertyNames = innerName.Split('.'); var lastIndex = propertyNames.Length - 1; for (var i = 0; i < propertyNames.Length; i++) { var propertyName = propertyNames[i]; if (i == lastIndex) { ctx.PushObject(current); ctx.PushProperty(propertyName); LoadSingleSimple(current.GetType(), current, propertyName, attrValue); ctx.PushProperty(propertyName); ctx.PopObject(); } else { var target = RuntimeUtil.GetPropertyValue(current, propertyName); if (target == null) { throw new XamlException("类型" + current.GetType().FullName + "的属性" + propertyName + "值为null,无法赋值"); } current = target; } } }
public void OnNewItem(IPoderosaLogItem item) { //カテゴリ分けなどあるかもしれないが... String text = String.Format("[{0}] {1}", item.Category.Name, item.Text); int width = PoderosaLogDocument.DefaultWidth; //width文字ごとに切り取り。日本語文字があるケースは未サポート int offset = 0; while (offset < text.Length) { int next = RuntimeUtil.AdjustIntRange(offset + width, 0, text.Length); GLine line = new GLine(text.Substring(offset, next - offset).ToCharArray(), new GWord(TextDecoration.ClonedDefault(), 0, CharGroup.Hankaku)); line.EOLType = next < text.Length? EOLType.Continue : EOLType.CRLF; Append(line); offset = next; } PoderosaLogViewControl vc = _session.CurrentView; if (vc != null) { if (vc.InvokeRequired) { vc.Invoke(vc.UpdateDocumentDelegate); } else { vc.UpdateDocument(); } } }
private object GetValueFromSource(object target) { if (_source == null) { return(null); } object value = null; var ui = _source as UIElement; if (ui != null) { value = ui.GetValue(_sourceProperty); } else { value = RuntimeUtil.GetPropertyValue(_source, this.PropertyName); } if (this.Converter != null) { value = this.Converter.Convert(value, this.Parameter); } return(value); }
/// <summary> /// Decrypt string. /// </summary> /// <param name="s">Base64-encoded encrypted data</param> /// <returns>decrypted text or null if failed</returns> public string DecryptString(string s) { if (s == null) { return(null); } if (s.Length == 0) { return(null); } using (ICryptoTransform transform = this.mCSP.CreateDecryptor(Convert.FromBase64String(CKEY), Convert.FromBase64String(CIV))) { try { byte[] buffer = Convert.FromBase64String(s); using (MemoryStream stream = new MemoryStream()) { using (CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Write)) { stream2.Write(buffer, 0, buffer.Length); stream2.FlushFinalBlock(); stream2.Close(); return(Encoding.UTF8.GetString(stream.ToArray())); } } } catch (Exception exception) { RuntimeUtil.SilentReportException(exception); return(null); } } }
private void OnOK(object sender, EventArgs args) { this.DialogResult = DialogResult.None; StringResource sr = SSHUtilPlugin.Instance.Strings; try { SSH2UserAuthKey key = SSH2UserAuthKey.FromSECSHStyleFile(_tKeyFile.Text, _tCurrentPassphrase.Text); if (_tNewPassphrase.Text != _tNewPassphraseAgain.Text) { GUtil.Warning(this, sr.GetString("Message.ChangePassphrase.PassphraseMismatch")); } else { if (_tNewPassphrase.Text.Length > 0 || GUtil.AskUserYesNo(this, sr.GetString("Message.ChangePassphrase.AskEmptyPassphrase")) == DialogResult.Yes) { FileStream s = new FileStream(_tKeyFile.Text, FileMode.Create); key.WritePrivatePartInSECSHStyleFile(s, "", _tNewPassphrase.Text); s.Close(); GUtil.Warning(this, sr.GetString("Message.ChangePassphrase.NotifyChanged"), MessageBoxIcon.Information); this.DialogResult = DialogResult.OK; this.Close(); } } } catch (Exception ex) { RuntimeUtil.ReportException(ex); GUtil.Warning(this, ex.Message); } }
/// <summary> /// Encrypt string. /// </summary> /// <param name="text">Text to encrypt</param> /// <returns>Base64-encoded encrypted data or null if failed</returns> public string EncryptString(string text) { if (text == null) { return(null); } try { using (ICryptoTransform transform = this.mCSP.CreateEncryptor(Convert.FromBase64String(CKEY), Convert.FromBase64String(CIV))) { byte[] bytes = Encoding.UTF8.GetBytes(text); using (MemoryStream stream = new MemoryStream()) { using (CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Write)) { stream2.Write(bytes, 0, bytes.Length); stream2.FlushFinalBlock(); stream2.Close(); return(Convert.ToBase64String(stream.ToArray())); } } } } catch (Exception exception) { RuntimeUtil.SilentReportException(exception); return(null); } }
private string fixCipherAlgorithms(string algorithms) { if (algorithms == null) { return(null); } string[] inputAlgorithms = algorithms.Split(';'); string[] defaultAlgorithms = DEFAULT_CIPHER_ALGORITHM_ORDER.Split(';'); string[] validAlgorithms = new string[defaultAlgorithms.Length]; int index = 0; foreach (string algo in inputAlgorithms) { for (int i = 0; i < defaultAlgorithms.Length; i++) { if (defaultAlgorithms[i] != null && defaultAlgorithms[i] == algo) { validAlgorithms[index++] = algo; defaultAlgorithms[i] = null; break; } } } foreach (string algo in defaultAlgorithms) { if (algo != null) { validAlgorithms[index++] = algo; } } return(RuntimeUtil.ConcatStrArray(validAlgorithms, ';')); }
private static CommandResult CmdPasteFromFile(ICommandTarget target) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Title = GEnv.Strings.GetString("Caption.SelectPasteFile"); dlg.Filter = "All Files(*.*)|*.*"; if (dlg.ShowDialog() == DialogResult.OK) { StreamReader r = null; try { ITerminalControlHost host = TerminalCommandTarget.AsOpenTerminal(target); if (host == null) { return(CommandResult.Failed); } r = new StreamReader(dlg.FileName, Encoding.Default); host.TerminalTransmission.SendTextStream(r, true); return(CommandResult.Succeeded); } catch (Exception ex) { RuntimeUtil.ReportException(ex); return(CommandResult.Failed); } finally { if (r != null) { r.Close(); } } } return(CommandResult.Cancelled); }
protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { base.OnClosing(e); try { if (SessionManagerPlugin.Instance == null) { return; //単体テストではSessionなしで起動することもありだ } IPoderosaDocument doc = _view.Document; if (doc == null) { return; } PrepareCloseResult r = SessionManagerPlugin.Instance.CloseDocument(doc); if (r == PrepareCloseResult.Cancel) { _closeCancelled = true; e.Cancel = true; } else { e.Cancel = false; } } catch (Exception ex) { RuntimeUtil.ReportException(ex); e.Cancel = false; //バグのためにウィンドウを閉じることもできない、というのはまずい } }
//コンテキストメニュー表示 public void ShowContextMenu(IPoderosaMenuGroup[] menus, ICommandTarget target, Point point_screen, ContextMenuFlags flags) { //まずソート ICollection sorted = PositionDesignationSorter.SortItems(menus); ContextMenuStrip cm = new ContextMenuStrip(); MenuUtil.BuildContextMenu(cm, new ConvertingEnumerable <IPoderosaMenuGroup>(sorted), target); if (cm.Items.Count == 0) { cm.Dispose(); return; } //キーボード操作をトリガにメニューを出すときは、選択があったほうが何かと操作しやすい。 if ((flags & ContextMenuFlags.SelectFirstItem) != ContextMenuFlags.None) { cm.Items[0].Select(); } // ContextMenuStrip is not disposed automatically and // its instance sits in memory till application end. // To release a document object related with some menu items, // we need to dispose ContextMenuStrip explicitly soon after it disappeared. cm.VisibleChanged += new EventHandler(ContextMenuStripVisibleChanged); try { cm.Show(this, this.PointToClient(point_screen)); } catch (Exception ex) { RuntimeUtil.ReportException(ex); } }
public void MousePosToTextPos(int mouseX, int mouseY, out int textX, out int textY) { SizeF pitch = GetRenderProfile().Pitch; textX = RuntimeUtil.AdjustIntRange((int)Math.Floor((mouseX - CharacterDocumentViewer.BORDER) / pitch.Width), 0, Int32.MaxValue); textY = RuntimeUtil.AdjustIntRange((int)Math.Floor((mouseY - CharacterDocumentViewer.BORDER) / (pitch.Height + GetRenderProfile().LineSpacing)), 0, Int32.MaxValue); }
/// <summary> /// /// </summary> /// <returns></returns> /// <exclude/> public Image GetImage() { try { if (!_imageLoadIsAttempted) { _imageLoadIsAttempted = true; _backgroundImage = null; if (_backgroundImageFileName != null && _backgroundImageFileName.Length > 0) { try { _backgroundImage = Image.FromFile(_backgroundImageFileName); } catch (Exception) { MessageBox.Show("Can't find the background image!", "Poderosa error", MessageBoxButtons.OK, MessageBoxIcon.Hand); } } } return(_backgroundImage); } catch (Exception ex) { RuntimeUtil.ReportException(ex); return(null); } }
public override void TerminatePlugin() { base.TerminatePlugin(); IStartupContextSupplier s = (IStartupContextSupplier)_poderosaWorld.GetAdapter(typeof(IStartupContextSupplier)); Flush(); //ファイルの有無に関わらず内部のStorageNodeは更新しとく if (s.PreferenceFileName != null) { string preferenceFileName = s.PreferenceFileName; string tempPreferenceFileName = preferenceFileName + ".tmp"; string prevPreferenceFileName = preferenceFileName + ".prev"; try { using (TextWriter writer = new StreamWriter(tempPreferenceFileName, false, System.Text.Encoding.Default)) { WritePreference(writer); } if (File.Exists(preferenceFileName)) { File.Delete(prevPreferenceFileName); File.Move(preferenceFileName, prevPreferenceFileName); } File.Move(tempPreferenceFileName, preferenceFileName); } catch (Exception ex) { RuntimeUtil.ReportException(ex); } } }
public void ApplySplitInfo(string format) { try { //現状を獲得 IPoderosaView[] previous_views = GetAllViews(); IPoderosaDocument[] documents = new IPoderosaDocument[previous_views.Length]; //分割適用後アクティブになるやつ for (int i = 0; i < previous_views.Length; i++) { documents[i] = previous_views[i].Document; } IPoderosaView[] new_views; SessionManagerPlugin sm = SessionManagerPlugin.Instance; if (format.Length > 0) { Form container = _parent.AsForm(); container.SuspendLayout(); Control old_root = this.RootControl; _paneDivision.ApplySplitInfo(old_root.Parent, old_root, format, delegate(string label) { return(CreateNewPane(_defaultViewFactory, DockStyle.Fill)); }); //とりあえずデフォルトファクトリで作成 container.ResumeLayout(true); _singlePane = null; //成功裏に終わったときのみ new_views = GetAllViews(); //新しいのを取得 } else { IContentReplaceableView view; UnifyAll(out view); new_views = new IPoderosaView[] { view }; } //既存ドキュメントに再適用 foreach (DocumentHost dh in sm.GetAllDocumentHosts()) { int index = CollectionUtil.ArrayIndexOf(previous_views, dh.LastAttachedView); if (index != -1) { IPoderosaView new_view = index < new_views.Length ? new_views[index] : new_views[0]; //個数が減ったら先頭に dh.AlternateView(new_view); } } //もともとActiveだったやつを再適用 for (int i = 0; i < documents.Length; i++) { if (documents[i] != null) { sm.AttachDocumentAndView(documents[i], sm.FindDocumentHost(documents[i]).LastAttachedView); //LastAttachedViewはこの上のループで適用済み } } } catch (Exception ex) { RuntimeUtil.ReportException(ex); } }
//選択モードに応じて範囲を定める。マウスでドラッグすることもあるので、column<0のケースも存在する public TextPoint ConvertSelectionPosition(GLine line, int column) { TextPoint result = new TextPoint(line.ID, column); int line_length = line.DisplayLength; if (_pivotType == RangeType.Line) { //行選択のときは、選択開始点以前のであったらその行の先頭、そうでないならその行のラスト。 //言い換えると(Pivot-Destination)を行頭・行末方向に拡大したものになるように if (result.Line <= _forwardPivot.Line) { result.Column = 0; } else { result.Column = line.DisplayLength; } } else //Word,Char選択 { if (result.Line < _forwardPivot.Line) //開始点より前のときは { if (result.Column < 0) { result.Column = 0; //行頭まで。 } else if (result.Column >= line_length) //行の右端の右まで選択しているときは、次行の先頭まで { result.Line++; result.Column = 0; } } else if (result.Line == _forwardPivot.Line) //同一行内選択.その行におさまるように { result.Column = RuntimeUtil.AdjustIntRange(result.Column, 0, line_length); } else //開始点の後方への選択 { if (result.Column < 0) { result.Line--; result.Column = line.PrevLine == null? 0 : line.PrevLine.DisplayLength; } else if (result.Column >= line_length) { //result.Column = line_length; /* KM 2012/10/07 22:36:28 * 矩形選択で文字のない場所を矩形の端点にする為コメントアウト。 * 最終的に文字列をコピーする時に、再度同様のチェックを行うので問題は生じない様だ。 */ } } } return(result); }
public void BypassDragDrop(DragEventArgs args) { try { WindowManagerPlugin.Instance.BypassDragDrop(_tabBarTable.ParentForm, args); } catch (Exception ex) { RuntimeUtil.ReportException(ex); } }
//更新 最終行が見えるように public void UpdateDocument() { PoderosaLogDocument doc = _session.Document; int newtop = RuntimeUtil.AdjustIntRange(doc.Size - this.GetHeightInLines(), 0, doc.Size - 1); AdjustScrollBar(); if (_VScrollBar.Enabled) _VScrollBar.Value = newtop; else Invalidate(); }
private static void CopyToClipboard(string data) { try { Clipboard.SetDataObject(data, false); } catch (Exception ex) { RuntimeUtil.ReportException(ex); } }
public static void Main(string[] args) { try { Run(args); } catch (Exception ex) { RuntimeUtil.ReportException(ex); } }