FlatCAMApp.py 478 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import threading
  16. import shutil
  17. from stat import S_IREAD, S_IRGRP, S_IROTH
  18. import subprocess
  19. import ctypes
  20. import winreg
  21. import tkinter as tk
  22. from PyQt5 import QtPrintSupport
  23. from contextlib import contextmanager
  24. import gc
  25. from xml.dom.minidom import parseString as parse_xml_string
  26. from multiprocessing.connection import Listener, Client
  27. from multiprocessing import Pool
  28. import socket
  29. from array import array
  30. # #######################################
  31. # # Imports part of FlatCAM ##
  32. # #######################################
  33. from ObjectCollection import *
  34. from FlatCAMObj import *
  35. from flatcamGUI.PlotCanvas import *
  36. from flatcamGUI.FlatCAMGUI import *
  37. from FlatCAMCommon import LoudDict
  38. from FlatCAMPostProc import load_postprocessors
  39. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  40. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  41. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  42. from FlatCAMProcess import *
  43. from FlatCAMWorkerStack import WorkerStack
  44. from flatcamGUI.VisPyVisuals import Color
  45. from vispy.gloo.util import _screenshot
  46. from vispy.io import write_png
  47. from flatcamTools import *
  48. import tclCommands
  49. import gettext
  50. import FlatCAMTranslation as fcTranslate
  51. import builtins
  52. fcTranslate.apply_language('strings')
  53. if '_' not in builtins.__dict__:
  54. _ = gettext.gettext
  55. # ########################################
  56. # # App ###
  57. # ########################################
  58. class App(QtCore.QObject):
  59. """
  60. The main application class. The constructor starts the GUI.
  61. """
  62. # Get Cmd Line Options
  63. cmd_line_shellfile = ''
  64. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  65. try:
  66. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  67. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  68. except getopt.GetoptError:
  69. print(cmd_line_help)
  70. sys.exit(2)
  71. for opt, arg in cmd_line_options:
  72. if opt == '-h':
  73. print(cmd_line_help)
  74. sys.exit()
  75. elif opt == '--shellfile':
  76. cmd_line_shellfile = arg
  77. # ## Logging ###
  78. log = logging.getLogger('base')
  79. log.setLevel(logging.DEBUG)
  80. # log.setLevel(logging.WARNING)
  81. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  82. handler = logging.StreamHandler()
  83. handler.setFormatter(formatter)
  84. log.addHandler(handler)
  85. # ##########################################################################
  86. # ################## Version and VERSION DATE ##############################
  87. # ##########################################################################
  88. version = 8.97
  89. version_date = "2019/09/15"
  90. beta = True
  91. # current date now
  92. date = str(datetime.today()).rpartition('.')[0]
  93. date = ''.join(c for c in date if c not in ':-')
  94. date = date.replace(' ', '_')
  95. # URL for update checks and statistics
  96. version_url = "http://flatcam.org/version"
  97. # App URL
  98. app_url = "http://flatcam.org"
  99. # Manual URL
  100. manual_url = "http://flatcam.org/manual/index.html"
  101. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  102. # this variable will hold the project status
  103. # if True it will mean that the project was modified and not saved
  104. should_we_save = False
  105. # flag is True if saving action has been triggered
  106. save_in_progress = False
  107. # ###########################################################################
  108. # ############################# Signals ################################
  109. # ###########################################################################
  110. # Inform the user
  111. # Handled by:
  112. # * App.info() --> Print on the status bar
  113. inform = QtCore.pyqtSignal(str)
  114. app_quit = QtCore.pyqtSignal()
  115. # General purpose background task
  116. worker_task = QtCore.pyqtSignal(dict)
  117. # File opened
  118. # Handled by:
  119. # * register_folder()
  120. # * register_recent()
  121. # Note: Setting the parameters to unicode does not seem
  122. # to have an effect. Then are received as Qstring
  123. # anyway.
  124. # File type and filename
  125. file_opened = QtCore.pyqtSignal(str, str)
  126. # File type and filename
  127. file_saved = QtCore.pyqtSignal(str, str)
  128. # Percentage of progress
  129. progress = QtCore.pyqtSignal(int)
  130. plots_updated = QtCore.pyqtSignal()
  131. # Emitted by new_object() and passes the new object as argument, plot flag.
  132. # on_object_created() adds the object to the collection, plots on appropriate flag
  133. # and emits new_object_available.
  134. object_created = QtCore.pyqtSignal(object, bool, bool)
  135. # Emitted when a object has been changed (like scaled, mirrored)
  136. object_changed = QtCore.pyqtSignal(object)
  137. # Emitted after object has been plotted.
  138. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  139. object_plotted = QtCore.pyqtSignal(object)
  140. # Emitted when a new object has been added or deleted from/to the collection
  141. object_status_changed = QtCore.pyqtSignal(object, str)
  142. message = QtCore.pyqtSignal(str, str, str)
  143. # Emmited when shell command is finished(one command only)
  144. shell_command_finished = QtCore.pyqtSignal(object)
  145. # Emitted when multiprocess pool has been recreated
  146. pool_recreated = QtCore.pyqtSignal(object)
  147. # Emitted when an unhandled exception happens
  148. # in the worker task.
  149. thread_exception = QtCore.pyqtSignal(object)
  150. # used to signal that there are arguments for the app
  151. args_at_startup = QtCore.pyqtSignal(list)
  152. # a reusable signal to replot a list of objects
  153. # should be disconnected after use so it can be reused
  154. replot_signal = pyqtSignal(list)
  155. def __init__(self, user_defaults=True, post_gui=None):
  156. """
  157. Starts the application.
  158. :return: app
  159. :rtype: App
  160. """
  161. App.log.info("FlatCAM Starting...")
  162. self.main_thread = QtWidgets.QApplication.instance().thread()
  163. # ############################################################################
  164. # # ################# OS-specific ############################################
  165. # ############################################################################
  166. portable = False
  167. # Folder for user settings.
  168. if sys.platform == 'win32':
  169. # #########################################################################
  170. # Setup the listening thread for another instance launching with args #####
  171. # #########################################################################
  172. # make sure the thread is stored by using a self. otherwise it's garbage collected
  173. self.th = QtCore.QThread()
  174. self.th.start(priority=QtCore.QThread.LowestPriority)
  175. self.new_launch = ArgsThread()
  176. self.new_launch.open_signal[list].connect(self.on_startup_args)
  177. self.new_launch.moveToThread(self.th)
  178. self.new_launch.start.emit()
  179. from win32com.shell import shell, shellcon
  180. if platform.architecture()[0] == '32bit':
  181. App.log.debug("Win32!")
  182. else:
  183. App.log.debug("Win64!")
  184. # #########################################################################
  185. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  186. # #########################################################################
  187. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  188. try:
  189. with open(config_file, 'r') as f:
  190. try:
  191. for line in f:
  192. param = str(line).rpartition('=')
  193. if param[0] == 'portable':
  194. try:
  195. portable = eval(param[2])
  196. except NameError:
  197. portable = False
  198. except Exception as e:
  199. log.debug('App.__init__() -->%s' % str(e))
  200. return
  201. except FileNotFoundError:
  202. pass
  203. if portable is False:
  204. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  205. else:
  206. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  207. self.os = 'windows'
  208. else: # Linux/Unix/MacOS
  209. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  210. self.os = 'unix'
  211. # ##########################################################################
  212. # ################## Setup folders and files ###############################
  213. # ##########################################################################
  214. if not os.path.exists(self.data_path):
  215. os.makedirs(self.data_path)
  216. App.log.debug('Created data folder: ' + self.data_path)
  217. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  218. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  219. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  220. if not os.path.exists(self.postprocessorpaths):
  221. os.makedirs(self.postprocessorpaths)
  222. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  223. # create current_defaults.FlatConfig file if there is none
  224. try:
  225. f = open(self.data_path + '/current_defaults.FlatConfig')
  226. f.close()
  227. except IOError:
  228. App.log.debug('Creating empty current_defaults.FlatConfig')
  229. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  230. json.dump({}, f)
  231. f.close()
  232. # create factory_defaults.FlatConfig file if there is none
  233. try:
  234. f = open(self.data_path + '/factory_defaults.FlatConfig')
  235. f.close()
  236. except IOError:
  237. App.log.debug('Creating empty factory_defaults.FlatConfig')
  238. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  239. json.dump({}, f)
  240. f.close()
  241. try:
  242. f = open(self.data_path + '/recent.json')
  243. f.close()
  244. except IOError:
  245. App.log.debug('Creating empty recent.json')
  246. f = open(self.data_path + '/recent.json', 'w')
  247. json.dump([], f)
  248. f.close()
  249. try:
  250. fp = open(self.data_path + '/recent_projects.json')
  251. fp.close()
  252. except IOError:
  253. App.log.debug('Creating empty recent_projects.json')
  254. fp = open(self.data_path + '/recent_projects.json', 'w')
  255. json.dump([], fp)
  256. fp.close()
  257. # Application directory. CHDIR to it. Otherwise, trying to load
  258. # GUI icons will fail as their path is relative.
  259. # This will fail under cx_freeze ...
  260. self.app_home = os.path.dirname(os.path.realpath(__file__))
  261. App.log.debug("Application path is " + self.app_home)
  262. App.log.debug("Started in " + os.getcwd())
  263. # cx_freeze workaround
  264. if os.path.isfile(self.app_home):
  265. self.app_home = os.path.dirname(self.app_home)
  266. os.chdir(self.app_home)
  267. # #############################################################################
  268. # ##################### CREATE MULTIPROCESSING POOL ###########################
  269. # #############################################################################
  270. self.pool = Pool()
  271. # ##########################################################################
  272. # ################## Setting the Splash Screen #############################
  273. # ##########################################################################
  274. settings = QSettings("Open Source", "FlatCAM")
  275. if settings.contains("splash_screen"):
  276. show_splash = settings.value("splash_screen")
  277. else:
  278. settings.setValue('splash_screen', 1)
  279. # This will write the setting to the platform specific storage.
  280. del settings
  281. show_splash = 1
  282. if show_splash:
  283. splash_pix = QtGui.QPixmap('share/splash.png')
  284. splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  285. # splash.setMask(splash_pix.mask())
  286. splash.show()
  287. splash.showMessage(_("FlatCAM is initializing ..."),
  288. alignment=Qt.AlignBottom | Qt.AlignLeft,
  289. color=QtGui.QColor("gray"))
  290. # #############################################################################
  291. # ##################### Initialize GUI ########################################
  292. # #############################################################################
  293. # FlatCAM colors used in plotting
  294. self.FC_light_green = '#BBF268BF'
  295. self.FC_dark_green = '#006E20BF'
  296. self.FC_light_blue = '#a5a5ffbf'
  297. self.FC_dark_blue = '#0000ffbf'
  298. QtCore.QObject.__init__(self)
  299. self.ui = FlatCAMGUI(self.version, self.beta, self)
  300. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  301. self.ui.final_save.connect(self.final_save)
  302. # #############################################################################
  303. # ############################## Data #########################################
  304. # #############################################################################
  305. self.recent = []
  306. self.recent_projects = []
  307. self.clipboard = QtWidgets.QApplication.clipboard()
  308. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  309. self.project_filename = None
  310. self.toggle_units_ignore = False
  311. # self.defaults_form = PreferencesUI()
  312. # when adding entries here read the comments in the method found bellow named:
  313. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  314. self.defaults_form_fields = {
  315. # General App
  316. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  317. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  318. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  319. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  320. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  321. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  322. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  323. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  324. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  325. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  326. "global_project_autohide": self.ui.general_defaults_form.general_app_group.project_autohide_cb,
  327. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_group.toggle_tooltips_cb,
  328. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  329. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  330. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  331. "global_delete_confirmation": self.ui.general_defaults_form.general_app_group.delete_conf_cb,
  332. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  333. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  334. # General GUI Preferences
  335. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  336. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  337. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  338. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  339. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  340. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  341. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  342. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  343. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  344. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  345. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  346. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  347. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  348. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  349. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  350. # General GUI Settings
  351. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  352. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  353. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  354. # Gerber General
  355. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  356. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  357. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  358. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  359. "gerber_buffering": self.ui.gerber_defaults_form.gerber_gen_group.buffering_radio,
  360. "gerber_simplification": self.ui.gerber_defaults_form.gerber_gen_group.simplify_cb,
  361. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_gen_group.simplification_tol_spinner,
  362. # Gerber Options
  363. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  364. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  365. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  366. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  367. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  368. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  369. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  370. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  371. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  372. # Gerber Advanced Options
  373. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  374. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  375. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  376. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  377. # Gerber Export
  378. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  379. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  380. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  381. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  382. # Gerber Editor
  383. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  384. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  385. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  386. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  387. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  388. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  389. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  390. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  391. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  392. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  393. "gerber_editor_circ_angle":
  394. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  395. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  396. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  397. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  398. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  399. # Excellon General
  400. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  401. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  402. "excellon_format_upper_in":
  403. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  404. "excellon_format_lower_in":
  405. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  406. "excellon_format_upper_mm":
  407. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  408. "excellon_format_lower_mm":
  409. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  410. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  411. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  412. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  413. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  414. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  415. # Excellon Options
  416. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  417. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  418. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  419. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  420. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_opt_group.spindledir_radio,
  421. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  422. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  423. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  424. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  425. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  426. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  427. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  428. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  429. # Excellon Advanced Options
  430. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  431. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  432. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  433. "excellon_endz": self.ui.excellon_defaults_form.excellon_adv_opt_group.eendz_entry,
  434. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  435. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  436. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  437. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  438. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  439. # Excellon Export
  440. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  441. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  442. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  443. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  444. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  445. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  446. # Excellon Editor
  447. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  448. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  449. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  450. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  451. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  452. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  453. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  454. "excellon_editor_circ_angle":
  455. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  456. # Excellon Slots
  457. "excellon_editor_slot_direction":
  458. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  459. "excellon_editor_slot_angle":
  460. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  461. "excellon_editor_slot_length":
  462. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  463. # Excellon Slots
  464. "excellon_editor_slot_array_size":
  465. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  466. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  467. "excellon_editor_slot_lin_pitch":
  468. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  469. "excellon_editor_slot_lin_angle":
  470. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  471. "excellon_editor_slot_circ_dir":
  472. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  473. "excellon_editor_slot_circ_angle":
  474. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  475. # Geometry General
  476. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  477. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  478. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  479. # Geometry Options
  480. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  481. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  482. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  483. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  484. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  485. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_opt_group.spindledir_radio,
  486. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  487. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  488. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  489. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  490. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  491. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  492. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  493. # Geometry Advanced Options
  494. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  495. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  496. "geometry_endz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gendz_entry,
  497. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  498. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  499. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  500. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  501. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  502. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  503. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  504. # Geometry Editor
  505. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  506. # CNCJob General
  507. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  508. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  509. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  510. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontsize_sp,
  511. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry,
  512. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  513. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  514. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  515. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  516. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  517. # CNC Job Options
  518. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  519. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  520. # CNC Job Advanced Options
  521. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  522. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  523. # NCC Tool
  524. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  525. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  526. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  527. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  528. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  529. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  530. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  531. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  532. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  533. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  534. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  535. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  536. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  537. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  538. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  539. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  540. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  541. # CutOut Tool
  542. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  543. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  544. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  545. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  546. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  547. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  548. # Paint Area Tool
  549. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  550. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  551. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  552. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  553. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  554. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  555. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  556. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  557. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  558. # 2-sided Tool
  559. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  560. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  561. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  562. # Film Tool
  563. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  564. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  565. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  566. # Panelize Tool
  567. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  568. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  569. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  570. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  571. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  572. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  573. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  574. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  575. # Calculators Tool
  576. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  577. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  578. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  579. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  580. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  581. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  582. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  583. # Transformations Tool
  584. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  585. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  586. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  587. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  588. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  589. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  590. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  591. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  592. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  593. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  594. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  595. # SolderPaste Dispensing Tool
  596. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  597. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  598. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  599. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  600. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  601. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  602. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  603. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  604. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  605. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  606. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  607. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  608. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  609. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  610. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  611. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  612. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  613. # file associations
  614. "fa_excellon": self.ui.fa_defaults_form.fa_excellon_group.exc_list_text,
  615. "fa_gcode": self.ui.fa_defaults_form.fa_gcode_group.gco_list_text,
  616. # "fa_geometry": self.ui.fa_defaults_form.fa_geometry_group.close_paths_cb,
  617. "fa_gerber": self.ui.fa_defaults_form.fa_gerber_group.grb_list_text,
  618. }
  619. # ############################
  620. # ### LOAD POSTPROCESSORS ####
  621. # ############################
  622. self.postprocessors = load_postprocessors(self)
  623. for name in list(self.postprocessors.keys()):
  624. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  625. if name.partition('_')[0] == 'Paste':
  626. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  627. continue
  628. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  629. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  630. if name == 'hpgl':
  631. continue
  632. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  633. # ############################
  634. # ### LOAD LANGUAGES ####
  635. # ############################
  636. self.languages = fcTranslate.load_languages()
  637. for name in sorted(self.languages.values()):
  638. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  639. self.defaults = LoudDict()
  640. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  641. self.defaults.update({
  642. # Global APP Preferences
  643. "first_run": True,
  644. "units": "IN",
  645. "global_serial": 0,
  646. "global_stats": {},
  647. "global_tabs_detachable": True,
  648. "global_app_level": 'b',
  649. "global_portable": False,
  650. "global_language": 'English',
  651. "global_version_check": True,
  652. "global_send_stats": True,
  653. "global_pan_button": '2',
  654. "global_mselect_key": 'Control',
  655. "global_project_at_startup": False,
  656. "global_project_autohide": True,
  657. "global_toggle_tooltips": True,
  658. "global_worker_number": 2,
  659. "global_tolerance": 0.01,
  660. "global_open_style": True,
  661. "global_delete_confirmation": True,
  662. "global_compression_level": 3,
  663. "global_save_compressed": True,
  664. # Global GUI Preferences
  665. "global_gridx": 0.0393701,
  666. "global_gridy": 0.0393701,
  667. "global_snap_max": 0.001968504,
  668. "global_workspace": False,
  669. "global_workspaceT": "A4P",
  670. "global_grid_context_menu": {
  671. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  672. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  673. },
  674. "global_plot_fill": '#BBF268BF',
  675. "global_plot_line": '#006E20BF',
  676. "global_sel_fill": '#a5a5ffbf',
  677. "global_sel_line": '#0000ffbf',
  678. "global_alt_sel_fill": '#BBF268BF',
  679. "global_alt_sel_line": '#006E20BF',
  680. "global_draw_color": '#FF0000',
  681. "global_sel_draw_color": '#0000FF',
  682. "global_proj_item_color": '#000000',
  683. "global_proj_item_dis_color": '#b7b7cb',
  684. "global_toolbar_view": 511,
  685. "global_background_timeout": 300000, # Default value is 5 minutes
  686. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  687. # (python trace only for unknown errors),
  688. # 1 = show trace(show trace always),
  689. # 2 = (For the future).
  690. # Persistence
  691. "global_last_folder": None,
  692. "global_last_save_folder": None,
  693. # Default window geometry
  694. "global_def_win_x": 100,
  695. "global_def_win_y": 100,
  696. "global_def_win_w": 1024,
  697. "global_def_win_h": 650,
  698. "global_def_notebook_width": 1,
  699. # Constants...
  700. "global_defaults_save_period_ms": 20000, # Time between default saves.
  701. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  702. "global_shell_at_startup": False, # Show the shell at startup.
  703. "global_recent_limit": 10, # Max. items in recent list.
  704. "fit_key": 'V',
  705. "zoom_out_key": '-',
  706. "zoom_in_key": '=',
  707. "grid_toggle_key": 'G',
  708. "global_zoom_ratio": 1.5,
  709. "global_point_clipboard_format": "(%.4f, %.4f)",
  710. "global_zdownrate": None,
  711. # General GUI Settings
  712. "global_hover": False,
  713. "global_selection_shape": True,
  714. "global_layout": "compact",
  715. # Gerber General
  716. "gerber_plot": True,
  717. "gerber_solid": True,
  718. "gerber_multicolored": False,
  719. "gerber_circle_steps": 128,
  720. "gerber_use_buffer_for_union": True,
  721. "gerber_buffering": "full",
  722. "gerber_simplification": False,
  723. "gerber_simp_tolerance": 0.0005,
  724. # Gerber Options
  725. "gerber_isotooldia": 0.00787402,
  726. "gerber_isopasses": 1,
  727. "gerber_isooverlap": 0.00393701,
  728. "gerber_milling_type": "cl",
  729. "gerber_combine_passes": False,
  730. "gerber_noncoppermargin": 0.00393701,
  731. "gerber_noncopperrounded": False,
  732. "gerber_bboxmargin": 0.00393701,
  733. "gerber_bboxrounded": False,
  734. # Gerber Advanced Options
  735. "gerber_aperture_display": False,
  736. "gerber_aperture_scale_factor": 1.0,
  737. "gerber_aperture_buffer_factor": 0.0,
  738. "gerber_follow": False,
  739. # Gerber Export
  740. "gerber_exp_units": 'IN',
  741. "gerber_exp_integer": 2,
  742. "gerber_exp_decimals": 4,
  743. "gerber_exp_zeros": 'L',
  744. # Gerber Editor
  745. "gerber_editor_sel_limit": 30,
  746. "gerber_editor_newcode": 10,
  747. "gerber_editor_newsize": 0.8,
  748. "gerber_editor_newtype": 'C',
  749. "gerber_editor_newdim": "0.5, 0.5",
  750. "gerber_editor_array_size": 5,
  751. "gerber_editor_lin_axis": 'X',
  752. "gerber_editor_lin_pitch": 1,
  753. "gerber_editor_lin_angle": 0.0,
  754. "gerber_editor_circ_dir": 'CW',
  755. "gerber_editor_circ_angle": 0.0,
  756. "gerber_editor_scale_f": 1.0,
  757. "gerber_editor_buff_f": 0.1,
  758. "gerber_editor_ma_low": 0.0,
  759. "gerber_editor_ma_high": 1.0,
  760. # Excellon General
  761. "excellon_plot": True,
  762. "excellon_solid": True,
  763. "excellon_format_upper_in": 2,
  764. "excellon_format_lower_in": 4,
  765. "excellon_format_upper_mm": 3,
  766. "excellon_format_lower_mm": 3,
  767. "excellon_zeros": "L",
  768. "excellon_units": "INCH",
  769. "excellon_update": True,
  770. "excellon_optimization_type": 'B',
  771. "excellon_search_time": 3,
  772. # Excellon Options
  773. "excellon_drillz": -0.0590551,
  774. "excellon_travelz": 0.0787402,
  775. "excellon_feedrate": 3.14961,
  776. "excellon_spindlespeed": None,
  777. "excellon_spindledir": 'CW',
  778. "excellon_dwell": False,
  779. "excellon_dwelltime": 1,
  780. "excellon_toolchange": False,
  781. "excellon_toolchangez": 0.5,
  782. "excellon_ppname_e": 'default',
  783. "excellon_tooldia": 0.0314961,
  784. "excellon_slot_tooldia": 0.0708661,
  785. "excellon_gcode_type": "drills",
  786. # Excellon Advanced Options
  787. "excellon_offset": 0.0,
  788. "excellon_toolchangexy": "0.0, 0.0",
  789. "excellon_startz": None,
  790. "excellon_endz": 0.5,
  791. "excellon_feedrate_rapid": 31.4961,
  792. "excellon_z_pdepth": -0.02,
  793. "excellon_feedrate_probe": 3.14961,
  794. "excellon_f_plunge": False,
  795. "excellon_f_retract": False,
  796. # Excellon Export
  797. "excellon_exp_units": 'INCH',
  798. "excellon_exp_format": 'ndec',
  799. "excellon_exp_integer": 2,
  800. "excellon_exp_decimals": 4,
  801. "excellon_exp_zeros": 'LZ',
  802. "excellon_exp_slot_type": 'routing',
  803. # Excellon Editor
  804. "excellon_editor_sel_limit": 30,
  805. "excellon_editor_newdia": 0.039,
  806. "excellon_editor_array_size": 5,
  807. "excellon_editor_lin_dir": 'X',
  808. "excellon_editor_lin_pitch": 0.1,
  809. "excellon_editor_lin_angle": 0.0,
  810. "excellon_editor_circ_dir": 'CW',
  811. "excellon_editor_circ_angle": 12,
  812. # Excellon Slots
  813. "excellon_editor_slot_direction": 'X',
  814. "excellon_editor_slot_angle": 0.0,
  815. "excellon_editor_slot_length": 5.0,
  816. # Excellon Slot Array
  817. "excellon_editor_slot_array_size": 5,
  818. "excellon_editor_slot_lin_dir": 'X',
  819. "excellon_editor_slot_lin_pitch": 0.1,
  820. "excellon_editor_slot_lin_angle": 0.0,
  821. "excellon_editor_slot_circ_dir": 'CW',
  822. "excellon_editor_slot_circ_angle": 0.0,
  823. # Geometry General
  824. "geometry_plot": True,
  825. "geometry_circle_steps": 128,
  826. "geometry_cnctooldia": "0.0944882",
  827. # Geometry Options
  828. "geometry_cutz": -0.0944882,
  829. "geometry_vtipdia": 0.1,
  830. "geometry_vtipangle": 30,
  831. "geometry_multidepth": False,
  832. "geometry_depthperpass": 0.0314961,
  833. "geometry_travelz": 0.0787402,
  834. "geometry_toolchange": False,
  835. "geometry_toolchangez": 0.5,
  836. "geometry_feedrate": 3.14961,
  837. "geometry_feedrate_z": 3.14961,
  838. "geometry_spindlespeed": None,
  839. "geometry_spindledir": 'CW',
  840. "geometry_dwell": False,
  841. "geometry_dwelltime": 1,
  842. "geometry_ppname_g": 'default',
  843. # Geometry Advanced Options
  844. "geometry_toolchangexy": "0.0, 0.0",
  845. "geometry_startz": None,
  846. "geometry_endz": 0.5,
  847. "geometry_feedrate_rapid": 3.14961,
  848. "geometry_extracut": False,
  849. "geometry_z_pdepth": -0.02,
  850. "geometry_f_plunge": False,
  851. "geometry_feedrate_probe": 3.14961,
  852. "geometry_segx": 0.0,
  853. "geometry_segy": 0.0,
  854. # Geometry Editor
  855. "geometry_editor_sel_limit": 30,
  856. # CNC Job General
  857. "cncjob_plot": True,
  858. "cncjob_plot_kind": 'all',
  859. "cncjob_annotation": True,
  860. "cncjob_annotation_fontsize": 9,
  861. "cncjob_annotation_fontcolor": '#990000',
  862. "cncjob_tooldia": 0.0393701,
  863. "cncjob_coords_type": "G90",
  864. "cncjob_coords_decimals": 4,
  865. "cncjob_fr_decimals": 2,
  866. "cncjob_steps_per_circle": 128,
  867. # CNC Job Options
  868. "cncjob_prepend": "",
  869. "cncjob_append": "",
  870. # CNC Job Advanced Options
  871. "cncjob_toolchange_macro": "",
  872. "cncjob_toolchange_macro_enable": False,
  873. "tools_ncctools": "0.0393701, 0.019685",
  874. "tools_nccorder": 'rev',
  875. "tools_nccoverlap": 0.015748,
  876. "tools_nccmargin": 0.0393701,
  877. "tools_nccmethod": "seed",
  878. "tools_nccconnect": True,
  879. "tools_ncccontour": True,
  880. "tools_nccrest": False,
  881. "tools_ncc_offset_choice": False,
  882. "tools_ncc_offset_value": 0.0000,
  883. "tools_nccref": 'itself',
  884. "tools_ncc_plotting": 'normal',
  885. "tools_nccmilling_type": 'cl',
  886. "tools_ncctool_type": 'V',
  887. "tools_ncccutz": -0.001968504,
  888. "tools_ncctipdia": 0.00393701,
  889. "tools_ncctipangle": 30,
  890. "tools_cutouttooldia": 0.0944882,
  891. "tools_cutoutkind": "single",
  892. "tools_cutoutmargin": 0.00393701,
  893. "tools_cutoutgapsize": 0.15748,
  894. "tools_gaps_ff": "4",
  895. "tools_cutout_convexshape": False,
  896. "tools_painttooldia": 0.023622,
  897. "tools_paintorder": 'rev',
  898. "tools_paintoverlap": 0.015748,
  899. "tools_paintmargin": 0.0,
  900. "tools_paintmethod": "seed",
  901. "tools_selectmethod": "single",
  902. "tools_pathconnect": True,
  903. "tools_paintcontour": True,
  904. "tools_paint_plotting": 'normal',
  905. "tools_2sided_mirror_axis": "X",
  906. "tools_2sided_axis_loc": "point",
  907. "tools_2sided_drilldia": 0.0393701,
  908. "tools_film_type": 'neg',
  909. "tools_film_boundary": 0.0393701,
  910. "tools_film_scale": 0,
  911. "tools_panelize_spacing_columns": 0,
  912. "tools_panelize_spacing_rows": 0,
  913. "tools_panelize_columns": 1,
  914. "tools_panelize_rows": 1,
  915. "tools_panelize_constrain": False,
  916. "tools_panelize_constrainx": 0.0,
  917. "tools_panelize_constrainy": 0.0,
  918. "tools_panelize_panel_type": 'gerber',
  919. "tools_calc_vshape_tip_dia": 0.007874,
  920. "tools_calc_vshape_tip_angle": 30,
  921. "tools_calc_vshape_cut_z": 0.000787,
  922. "tools_calc_electro_length": 10.0,
  923. "tools_calc_electro_width": 10.0,
  924. "tools_calc_electro_cdensity": 13.0,
  925. "tools_calc_electro_growth": 10.0,
  926. "tools_transform_rotate": 90,
  927. "tools_transform_skew_x": 0.0,
  928. "tools_transform_skew_y": 0.0,
  929. "tools_transform_scale_x": 1.0,
  930. "tools_transform_scale_y": 1.0,
  931. "tools_transform_scale_link": True,
  932. "tools_transform_scale_reference": True,
  933. "tools_transform_offset_x": 0.0,
  934. "tools_transform_offset_y": 0.0,
  935. "tools_transform_mirror_reference": False,
  936. "tools_transform_mirror_point": (0, 0),
  937. "tools_solderpaste_tools": "0.0393701, 0.011811",
  938. "tools_solderpaste_new": 0.011811,
  939. "tools_solderpaste_z_start": 0.00019685039,
  940. "tools_solderpaste_z_dispense": 0.00393701,
  941. "tools_solderpaste_z_stop": 0.00019685039,
  942. "tools_solderpaste_z_travel": 0.00393701,
  943. "tools_solderpaste_z_toolchange": 0.0393701,
  944. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  945. "tools_solderpaste_frxy": 3.0,
  946. "tools_solderpaste_frz": 3.0,
  947. "tools_solderpaste_frz_dispense": 0.0393701,
  948. "tools_solderpaste_speedfwd": 20,
  949. "tools_solderpaste_dwellfwd": 1,
  950. "tools_solderpaste_speedrev": 10,
  951. "tools_solderpaste_dwellrev": 1,
  952. "tools_solderpaste_pp": 'Paste_1',
  953. "tools_sub_close_paths": True,
  954. # file associations
  955. "fa_excellon": ".drl, .xln, .drd, .tap, .exc, .ncd",
  956. "fa_gcode": ".nc, .ncc, .tap, .gcode, .cnc, .ecs, .fnc, .dnc, .ncg, .gc, .fan, .fgc, .din, .xpi,"
  957. " .hnc, .h, .i, .ncp, .min, .gcd, .rol, .mpr, .ply, .out, .eia, .plt, .sbp, .mpf",
  958. "fa_gerber": ".gbr, .ger, .gtl, .gbl, .gts, .gbs, .gtp, .gbp, .gto, .gbo, .gm1, .gml, .gm3, .gko, .cmp, "
  959. ".sol, .stc, .sts, .plc, .pls, .crc, .crs, .tsm, .bsm, .ly2, .ly15, .dim, .mil, .grb, .top, "
  960. ".bot, .smt, .smb, .sst, .ssb, .spt, .spb, .pho, .gdo, .art, .gbd",
  961. })
  962. # ############################################################
  963. # ############### Load defaults from file ####################
  964. # ############################################################
  965. if user_defaults:
  966. self.load_defaults(filename='current_defaults')
  967. # #############################################################
  968. # ############## APPLY APP LANGUAGE ###########################
  969. # #############################################################
  970. ret_val = fcTranslate.apply_language('strings')
  971. if ret_val == "no language":
  972. self.inform.emit('[ERROR] %s' %
  973. _("Could not find the Language files. The App strings are missing."))
  974. log.debug("Could not find the Language files. The App strings are missing.")
  975. else:
  976. # make the current language the current selection on the language combobox
  977. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  978. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  979. # ##############################################################
  980. # ################# CREATE UNIQUE SERIAL NUMBER ################
  981. # ##############################################################
  982. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  983. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  984. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  985. self.save_defaults(silent=True)
  986. self.propagate_defaults(silent=True)
  987. self.restore_main_win_geom()
  988. def auto_save_defaults():
  989. try:
  990. self.save_defaults(silent=True)
  991. self.propagate_defaults(silent=True)
  992. finally:
  993. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  994. # the following lines activates automatic defaults save
  995. # if user_defaults:
  996. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  997. # self.options_form = PreferencesUI()
  998. self.options_form_fields = {
  999. "units": self.ui.general_options_form.general_app_group.units_radio,
  1000. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  1001. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  1002. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  1003. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  1004. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  1005. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  1006. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  1007. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  1008. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  1009. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  1010. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  1011. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  1012. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  1013. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  1014. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  1015. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  1016. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  1017. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  1018. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1019. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1020. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  1021. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  1022. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  1023. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  1024. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  1025. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  1026. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  1027. "excellon_spindledir": self.ui.excellon_options_form.excellon_opt_group.spindledir_radio,
  1028. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  1029. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  1030. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  1031. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  1032. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  1033. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  1034. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1035. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  1036. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  1037. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  1038. "excellon_endz": self.ui.excellon_options_form.excellon_adv_opt_group.eendz_entry,
  1039. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  1040. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  1041. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  1042. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  1043. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  1044. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  1045. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  1046. "geometry_spindledir": self.ui.geometry_options_form.geometry_opt_group.spindledir_radio,
  1047. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  1048. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  1049. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  1050. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  1051. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  1052. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  1053. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  1054. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  1055. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  1056. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1057. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  1058. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  1059. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  1060. "geometry_endz": self.ui.geometry_options_form.geometry_adv_opt_group.gendz_entry,
  1061. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  1062. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  1063. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  1064. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  1065. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  1066. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  1067. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  1068. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  1069. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  1070. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  1071. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  1072. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  1073. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  1074. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  1075. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  1076. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  1077. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1078. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1079. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1080. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1081. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1082. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1083. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1084. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1085. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1086. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1087. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1088. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1089. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1090. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1091. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1092. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1093. }
  1094. for name in list(self.postprocessors.keys()):
  1095. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1096. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1097. self.options = LoudDict()
  1098. self.options.set_change_callback(self.on_options_dict_change)
  1099. self.options.update({
  1100. "units": "IN",
  1101. "global_gridx": 1.0,
  1102. "global_gridy": 1.0,
  1103. "global_snap_max": 0.05,
  1104. "global_background_timeout": 300000, # Default value is 5 minutes
  1105. "global_verbose_error_level": 0, # Shell verbosity:
  1106. # 0 = default(python trace only for unknown errors),
  1107. # 1 = show trace(show trace allways), 2 = (For the future).
  1108. "gerber_plot": True,
  1109. "gerber_solid": True,
  1110. "gerber_multicolored": False,
  1111. "gerber_isotooldia": 0.016,
  1112. "gerber_isopasses": 1,
  1113. "gerber_isooverlap": 0.15,
  1114. "gerber_combine_passes": True,
  1115. "gerber_noncoppermargin": 0.0,
  1116. "gerber_noncopperrounded": False,
  1117. "gerber_bboxmargin": 0.0,
  1118. "gerber_bboxrounded": False,
  1119. "excellon_plot": True,
  1120. "excellon_solid": False,
  1121. "excellon_format_upper_in": 2,
  1122. "excellon_format_lower_in": 4,
  1123. "excellon_format_upper_mm": 3,
  1124. "excellon_format_lower_mm": 3,
  1125. "excellon_units": 'INCH',
  1126. "excellon_optimization_type": 'B',
  1127. "excellon_search_time": 3,
  1128. "excellon_zeros": "L",
  1129. "excellon_drillz": -0.1,
  1130. "excellon_travelz": 0.1,
  1131. "excellon_feedrate": 3.0,
  1132. "excellon_feedrate_rapid": 3.0,
  1133. "excellon_spindlespeed": None,
  1134. "excellon_spindledir": 'CW',
  1135. "excellon_dwell": True,
  1136. "excellon_dwelltime": 1000,
  1137. "excellon_toolchange": False,
  1138. "excellon_toolchangez": 1.0,
  1139. "excellon_toolchangexy": "0.0, 0.0",
  1140. "excellon_tooldia": 0.016,
  1141. "excellon_ppname_e": 'default',
  1142. "excellon_f_plunge": False,
  1143. "excellon_startz": None,
  1144. "excellon_endz": 2.0,
  1145. "geometry_plot": True,
  1146. "geometry_segx": 0.0,
  1147. "geometry_segy": 0.0,
  1148. "geometry_cutz": -0.002,
  1149. "geometry_vtipdia": 0.1,
  1150. "geometry_vtipangle": 30,
  1151. "geometry_travelz": 0.1,
  1152. "geometry_feedrate": 3.0,
  1153. "geometry_feedrate_z": 3.0,
  1154. "geometry_feedrate_rapid": 3.0,
  1155. "geometry_spindlespeed": None,
  1156. "geometry_spindledir": 'CW',
  1157. "geometry_dwell": True,
  1158. "geometry_dwelltime": 1000,
  1159. "geometry_cnctooldia": 0.016,
  1160. "geometry_toolchange": False,
  1161. "geometry_toolchangez": 2.0,
  1162. "geometry_toolchangexy": "0.0, 0.0",
  1163. "geometry_startz": None,
  1164. "geometry_endz": 2.0,
  1165. "geometry_ppname_g": "default",
  1166. "geometry_f_plunge": False,
  1167. "geometry_depthperpass": 0.002,
  1168. "geometry_multidepth": False,
  1169. "geometry_extracut": False,
  1170. "cncjob_plot": True,
  1171. "cncjob_tooldia": 0.016,
  1172. "cncjob_prepend": "",
  1173. "cncjob_append": "",
  1174. "tools_ncctools": "1.0, 0.5",
  1175. "tools_nccoverlap": 0.4,
  1176. "tools_nccmargin": 1,
  1177. "tools_cutouttooldia": 0.07,
  1178. "tools_cutoutmargin": 0.1,
  1179. "tools_cutoutgapsize": 0.15,
  1180. "tools_gaps_ff": "8",
  1181. "tools_painttooldia": 0.07,
  1182. "tools_paintoverlap": 0.15,
  1183. "tools_paintmargin": 0.0,
  1184. "tools_paintmethod": "seed",
  1185. "tools_selectmethod": "single",
  1186. "tools_pathconnect": True,
  1187. "tools_paintcontour": True,
  1188. "tools_2sided_mirror_axis": "X",
  1189. "tools_2sided_axis_loc": 'point',
  1190. "tools_2sided_drilldia": 1,
  1191. "tools_film_type": 'neg',
  1192. "tools_film_boundary": 1,
  1193. "tools_film_scale": 0,
  1194. "tools_panelize_spacing_columns": 0,
  1195. "tools_panelize_spacing_rows": 0,
  1196. "tools_panelize_columns": 1,
  1197. "tools_panelize_rows": 1,
  1198. "tools_panelize_constrain": False,
  1199. "tools_panelize_constrainx": 0.0,
  1200. "tools_panelize_constrainy": 0.0
  1201. })
  1202. self.options.update(self.defaults) # Copy app defaults to project options
  1203. self.gen_form = None
  1204. self.ger_form = None
  1205. self.exc_form = None
  1206. self.geo_form = None
  1207. self.cnc_form = None
  1208. self.tools_form = None
  1209. self.fa_form = None
  1210. self.on_options_combo_change(0) # Will show the initial form
  1211. # ################################
  1212. # ### Initialize the color box's color in Preferences -> Global -> Color
  1213. # Init Plot Colors
  1214. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1215. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1216. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1217. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1218. int(self.defaults['global_plot_fill'][7:9], 16))
  1219. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1220. int(self.defaults['global_plot_fill'][7:9], 16))
  1221. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1222. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1223. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1224. # Init Left-Right Selection colors
  1225. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1226. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1227. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1228. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1229. int(self.defaults['global_sel_fill'][7:9], 16))
  1230. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1231. int(self.defaults['global_sel_fill'][7:9], 16))
  1232. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1233. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1234. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1235. # Init Right-Left Selection colors
  1236. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1237. self.defaults['global_alt_sel_fill'])
  1238. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1239. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1240. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1241. int(self.defaults['global_sel_fill'][7:9], 16))
  1242. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1243. int(self.defaults['global_sel_fill'][7:9], 16))
  1244. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1245. self.defaults['global_alt_sel_line'])
  1246. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1247. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1248. # Init Draw color and Selection Draw Color
  1249. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1250. self.defaults['global_draw_color'])
  1251. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1252. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1253. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1254. self.defaults['global_sel_draw_color'])
  1255. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1256. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1257. # Init Project Items color
  1258. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1259. self.defaults['global_proj_item_color'])
  1260. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1261. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1262. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1263. self.defaults['global_proj_item_dis_color'])
  1264. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1265. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1266. # Init the Annotation CNC Job color
  1267. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.set_value(
  1268. self.defaults['cncjob_annotation_fontcolor'])
  1269. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  1270. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1271. # ### End of Data ####
  1272. # ###############################################
  1273. # ############# SETUP Plot Area #################
  1274. # ###############################################
  1275. if show_splash:
  1276. splash.showMessage(_("FlatCAM is initializing ...\n"
  1277. "Canvas initialization started."),
  1278. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1279. color=QtGui.QColor("gray"))
  1280. start_plot_time = time.time() # debug
  1281. self.plotcanvas = None
  1282. self.app_cursor = None
  1283. self.hover_shapes = None
  1284. self.on_plotcanvas_setup()
  1285. end_plot_time = time.time()
  1286. used_time = end_plot_time - start_plot_time
  1287. self.log.debug("Finished Canvas initialization in %s seconds." % str(used_time))
  1288. if show_splash:
  1289. splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1290. "Canvas initialization started.\n"
  1291. "Canvas initialization finished in"), '%.2f' % used_time),
  1292. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1293. color=QtGui.QColor("gray"))
  1294. self.ui.splitter.setStretchFactor(1, 2)
  1295. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1296. # depending on from where those tools are called different actions can be done
  1297. self.call_source = 'app'
  1298. # ##############################################
  1299. # ######### SETUP OBJECT COLLECTION ############
  1300. # ##############################################
  1301. self.collection = ObjectCollection(self)
  1302. self.ui.project_tab_layout.addWidget(self.collection.view)
  1303. # ### Adjust tabs width ## ##
  1304. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1305. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1306. self.collection.view.setMinimumWidth(290)
  1307. self.log.debug("Finished creating Object Collection.")
  1308. # ###############################################
  1309. # ############# Worker SETUP ####################
  1310. # ###############################################
  1311. if self.defaults["global_worker_number"]:
  1312. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1313. else:
  1314. self.workers = WorkerStack(workers_number=2)
  1315. self.worker_task.connect(self.workers.add_task)
  1316. self.log.debug("Finished creating Workers crew.")
  1317. # ################################################
  1318. # ############### Signal handling ################
  1319. # ################################################
  1320. # ############# Custom signals ##################
  1321. # signal for displaying messages in status bar
  1322. self.inform.connect(self.info)
  1323. # signal to be called when the app is quiting
  1324. self.app_quit.connect(self.quit_application)
  1325. self.message.connect(self.message_dialog)
  1326. self.progress.connect(self.set_progress_bar)
  1327. # signals that are emitted when object state changes
  1328. self.object_created.connect(self.on_object_created)
  1329. self.object_changed.connect(self.on_object_changed)
  1330. self.object_plotted.connect(self.on_object_plotted)
  1331. self.plots_updated.connect(self.on_plots_updated)
  1332. # signals emitted when file state change
  1333. self.file_opened.connect(self.register_recent)
  1334. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1335. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1336. # ############# Standard signals ###################
  1337. # ### Menu
  1338. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1339. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1340. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1341. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1342. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1343. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1344. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1345. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1346. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1347. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1348. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1349. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1350. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1351. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1352. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1353. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1354. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1355. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1356. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1357. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1358. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1359. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1360. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1361. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1362. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1363. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1364. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1365. self.ui.menufile_exit.triggered.connect(self.final_save)
  1366. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1367. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1368. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1369. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1370. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1371. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1372. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1373. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1374. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1375. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1376. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1377. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1378. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1379. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1380. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1381. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1382. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1383. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1384. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1385. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1386. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1387. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1388. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1389. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1390. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1391. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1392. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1393. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1394. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1395. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1396. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1397. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1398. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1399. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1400. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1401. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1402. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1403. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1404. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1405. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1406. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1407. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1408. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1409. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1410. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1411. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1412. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1413. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1414. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1415. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1416. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1417. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1418. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1419. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1420. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1421. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1422. # ToolBar signals
  1423. self.connect_toolbar_signals()
  1424. # Notebook signals
  1425. # make the right click on the notebook tab connect to a function
  1426. self.ui.notebook.setupContextMenu()
  1427. self.ui.notebook.addContextMenu(
  1428. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1429. initial_checked=self.defaults["global_tabs_detachable"])
  1430. # activate initial state
  1431. self.on_notebook_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1432. # Context Menu
  1433. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1434. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1435. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1436. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1437. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1438. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1439. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1440. self.ui.clearplot.triggered.connect(self.clear_plots)
  1441. self.ui.replot.triggered.connect(self.plot_all)
  1442. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1443. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1444. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1445. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1446. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1447. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1448. # Preferences Plot Area TAB
  1449. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1450. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1451. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1452. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1453. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1454. # ##############################
  1455. # ### GUI PREFERENCES SIGNALS ##
  1456. # ##############################
  1457. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1458. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1459. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1460. )
  1461. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1462. lambda: self.on_toggle_units(no_pref=False))
  1463. # ###############################################################
  1464. # ################### GUI COLORS SIGNALS ########################
  1465. # ###############################################################
  1466. # Setting plot colors signals
  1467. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1468. self.on_pf_color_entry)
  1469. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1470. self.on_pf_color_button)
  1471. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1472. self.on_pf_color_spinner)
  1473. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1474. self.on_pf_color_slider)
  1475. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1476. self.on_pl_color_entry)
  1477. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1478. self.on_pl_color_button)
  1479. # Setting selection (left - right) colors signals
  1480. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1481. self.on_sf_color_entry)
  1482. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1483. self.on_sf_color_button)
  1484. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1485. self.on_sf_color_spinner)
  1486. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1487. self.on_sf_color_slider)
  1488. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1489. self.on_sl_color_entry)
  1490. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1491. self.on_sl_color_button)
  1492. # Setting selection (right - left) colors signals
  1493. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1494. self.on_alt_sf_color_entry)
  1495. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1496. self.on_alt_sf_color_button)
  1497. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1498. self.on_alt_sf_color_spinner)
  1499. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1500. self.on_alt_sf_color_slider)
  1501. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1502. self.on_alt_sl_color_entry)
  1503. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1504. self.on_alt_sl_color_button)
  1505. # Setting Editor Draw colors signals
  1506. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1507. self.on_draw_color_entry)
  1508. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1509. self.on_draw_color_button)
  1510. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1511. self.on_sel_draw_color_entry)
  1512. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1513. self.on_sel_draw_color_button)
  1514. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1515. self.on_proj_color_entry)
  1516. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1517. self.on_proj_color_button)
  1518. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1519. self.on_proj_color_dis_entry)
  1520. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1521. self.on_proj_color_dis_button)
  1522. # ########## workspace setting signals ###########
  1523. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1524. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1525. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1526. # ########## CNC Job related signals #############
  1527. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1528. self.on_cnc_custom_parameters)
  1529. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.editingFinished.connect(
  1530. self.on_annotation_fontcolor_entry)
  1531. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.clicked.connect(
  1532. self.on_annotation_fontcolor_button)
  1533. # ########## Modify G-CODE Plot Area TAB ###########
  1534. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1535. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1536. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1537. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1538. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1539. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1540. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1541. # portability changed signal
  1542. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1543. # Object list
  1544. self.collection.view.activated.connect(self.on_row_activated)
  1545. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1546. self.ui.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1547. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1548. # Export Excellon parameters.
  1549. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1550. self.on_update_exc_export
  1551. )
  1552. # call it once to make sure it is updated at startup
  1553. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1554. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1555. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1556. self.on_excellon_defaults_button)
  1557. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1558. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1559. self.on_excellon_options_button)
  1560. # when there are arguments at application startup this get launched
  1561. self.args_at_startup[list].connect(lambda: self.on_startup_args())
  1562. # connect the 'Apply' buttons from the Preferences/File Associations
  1563. self.ui.fa_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1564. lambda: self.on_register_files(obj_type='excellon'))
  1565. self.ui.fa_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1566. lambda: self.on_register_files(obj_type='gcode'))
  1567. self.ui.fa_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1568. lambda: self.on_register_files(obj_type='gerber'))
  1569. # splash screen button signal
  1570. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1571. # connect the abort_all_tasks related slots to the related signals
  1572. self.proc_container.idle_flag.connect(self.app_is_idle)
  1573. # #####################################################################################
  1574. # ########### FINISHED CONNECTING SIGNALS #############################################
  1575. # #####################################################################################
  1576. self.log.debug("Finished connecting Signals.")
  1577. # #####################################################################################
  1578. # ########################## Other setups #############################################
  1579. # #####################################################################################
  1580. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1581. self.tool_tab_locked = False
  1582. # decide if to show or hide the Notebook side of the screen at startup
  1583. if self.defaults["global_project_at_startup"] is True:
  1584. self.ui.splitter.setSizes([1, 1])
  1585. else:
  1586. self.ui.splitter.setSizes([0, 1])
  1587. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1588. self.setup_obj_classes()
  1589. self.setup_recent_items()
  1590. self.setup_component_editor()
  1591. # #####################################################################################
  1592. # ######################### Auto-complete KEYWORDS ####################################
  1593. # #####################################################################################
  1594. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1595. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1596. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1597. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1598. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1599. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1600. 'mirror', 'ncc',
  1601. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1602. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'paint',
  1603. 'pan', 'panel', 'panelize', 'plot', 'save', 'save_project', 'save_sys', 'scale',
  1604. 'set_active', 'set_sys', 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1605. 'version', 'write_gcode'
  1606. ]
  1607. self.ordinary_keywords = ['all', 'angle_x', 'angle_y', 'axis', 'axisoffset', 'box', 'center_x', 'center_y',
  1608. 'columns', 'combine', 'connect', 'contour', 'depthperpass', 'dia', 'diatol', 'dist',
  1609. 'drilled_dias', 'drillz', 'pp',
  1610. 'endz', 'extracut', 'factor', 'False', 'false', 'feedrate', 'feedrate_rapid',
  1611. 'filename', 'follow', 'gaps', 'gapsize', 'grid', 'gridoffset', 'gridoffsetx',
  1612. 'gridoffsety', 'gridx', 'gridy', 'has_offset', 'holes', 'margin', 'method',
  1613. 'milled_dias',
  1614. 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order', 'outname',
  1615. 'overlap', 'passes', 'postamble', 'ppname_e', 'ppname_g', 'preamble', 'radius', 'ref',
  1616. 'rest', 'rows', 'scale_factor', 'spacing_columns', 'spacing_rows', 'spindlespeed',
  1617. 'toolchange', 'toolchangez', 'tooldia', 'tools', 'travelz', 'True', 'true', 'type',
  1618. 'use_threads', 'value', 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move',
  1619. 'default', 'feedrate_z', 'grbl_11', 'grbl_laser', 'hpgl', 'line_xyz', 'marlin',
  1620. 'Paste_1', 'Repetier', 'Toolchange_Custom', 'Roland_MDX_20', 'Toolchange_manual',
  1621. 'Toolchange_Probe_MACH3', 'dwell', 'dwelltime', 'toolchange_xy'
  1622. ]
  1623. self.tcl_keywords = [
  1624. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1625. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1626. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1627. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1628. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1629. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1630. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1631. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1632. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1633. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1634. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1635. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1636. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1637. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1638. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1639. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1640. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1641. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1642. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1643. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1644. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1645. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1646. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1647. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1648. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1649. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1650. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1651. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1652. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1653. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1654. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1655. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1656. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1657. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1658. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1659. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1660. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1661. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1662. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1663. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1664. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1665. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1666. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1667. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1668. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1669. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1670. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1671. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1672. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1673. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1674. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1675. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1676. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1677. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1678. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1679. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1680. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1681. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1682. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1683. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1684. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1685. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1686. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1687. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1688. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1689. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1690. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1691. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1692. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1693. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1694. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1695. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1696. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1697. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1698. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1699. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1700. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1701. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1702. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1703. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1704. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1705. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1706. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1707. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1708. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1709. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1710. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1711. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1712. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1713. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1714. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1715. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1716. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1717. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1718. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1719. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1720. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1721. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1722. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1723. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1724. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1725. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1726. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1727. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1728. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1729. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1730. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1731. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1732. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1733. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1734. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1735. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1736. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1737. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1738. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1739. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1740. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1741. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1742. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1743. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1744. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1745. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1746. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1747. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1748. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1749. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1750. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1751. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1752. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1753. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1754. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1755. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1756. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1757. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1758. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1759. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1760. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1761. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1762. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1763. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1764. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1765. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1766. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1767. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1768. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1769. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1770. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1771. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1772. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1773. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1774. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1775. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1776. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1777. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1778. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1779. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1780. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1781. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1782. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1783. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1784. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1785. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1786. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1787. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1788. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1789. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1790. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1791. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1792. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1793. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1794. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1795. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1796. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1797. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1798. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1799. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1800. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1801. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1802. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1803. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1804. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1805. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1806. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1807. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1808. ]
  1809. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords + self.tcl_keywords
  1810. # ####################################################################################
  1811. # ####################### Shell SETUP ################################################
  1812. # ####################################################################################
  1813. self.shell = FCShell(self, version=self.version)
  1814. self.shell._edit.set_model_data(self.myKeywords)
  1815. self.ui.code_editor.set_model_data(self.myKeywords)
  1816. self.shell.setWindowIcon(self.ui.app_icon)
  1817. self.shell.setWindowTitle("FlatCAM Shell")
  1818. self.shell.resize(*self.defaults["global_shell_shape"])
  1819. self.shell.append_output("FlatCAM %s - " % self.version)
  1820. self.shell.append_output(_("Open Source Software - Type help to get started\n\n"))
  1821. self.init_tcl()
  1822. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1823. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1824. self.ui.shell_dock.setWidget(self.shell)
  1825. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1826. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1827. QtWidgets.QDockWidget.DockWidgetFloatable |
  1828. QtWidgets.QDockWidget.DockWidgetClosable)
  1829. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1830. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1831. if self.defaults["global_shell_at_startup"]:
  1832. self.ui.shell_dock.show()
  1833. else:
  1834. self.ui.shell_dock.hide()
  1835. # ##################################################################################
  1836. # ###################### Tools and Plugins #########################################
  1837. # ##################################################################################
  1838. self.dblsidedtool = None
  1839. self.measurement_tool = None
  1840. self.panelize_tool = None
  1841. self.film_tool = None
  1842. self.paste_tool = None
  1843. self.calculator_tool = None
  1844. self.sub_tool = None
  1845. self.move_tool = None
  1846. self.cutout_tool = None
  1847. self.ncclear_tool = None
  1848. self.paint_tool = None
  1849. self.transform_tool = None
  1850. self.properties_tool = None
  1851. self.pdf_tool = None
  1852. self.image_tool = None
  1853. self.pcb_wizard_tool = None
  1854. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1855. self.install_tools()
  1856. # ### System Font Parsing ###
  1857. # self.f_parse = ParseFont(self)
  1858. # self.parse_system_fonts()
  1859. # #####################################################################################
  1860. # ########################## START-UP ARGUMENTS #######################################
  1861. # #####################################################################################
  1862. # test if the program was started with a script as parameter
  1863. if self.cmd_line_shellfile:
  1864. try:
  1865. with open(self.cmd_line_shellfile, "r") as myfile:
  1866. cmd_line_shellfile_text = myfile.read()
  1867. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1868. except Exception as ext:
  1869. print("ERROR: ", ext)
  1870. sys.exit(2)
  1871. # #####################################################################################
  1872. # ######################## Check for updates ##########################################
  1873. # #####################################################################################
  1874. # Separate thread (Not worker)
  1875. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1876. if (self.beta is False or self.beta is None) and \
  1877. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1878. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1879. self.thr2 = QtCore.QThread()
  1880. self.worker_task.emit({'fcn': self.version_check,
  1881. 'params': []})
  1882. self.thr2.start(QtCore.QThread.LowPriority)
  1883. # #####################################################################################
  1884. # ###################### Variables for global usage ###################################
  1885. # #####################################################################################
  1886. # register files with FlatCAM; it works only for Windows for now
  1887. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1888. self.on_register_files()
  1889. # coordinates for relative position display
  1890. self.rel_point1 = (0, 0)
  1891. self.rel_point2 = (0, 0)
  1892. # variable to store coordinates
  1893. self.pos = (0, 0)
  1894. self.pos_jump = (0, 0)
  1895. # variable to store mouse coordinates
  1896. self.mouse = [0, 0]
  1897. # decide if we have a double click or single click
  1898. self.doubleclick = False
  1899. # variable to store if a command is active (then the var is not None) and which one it is
  1900. self.command_active = None
  1901. # variable to store the status of moving selection action
  1902. # None value means that it's not an selection action
  1903. # True value = a selection from left to right
  1904. # False value = a selection from right to left
  1905. self.selection_type = None
  1906. # List to store the objects that are currently loaded in FlatCAM
  1907. # This list is updated on each object creation or object delete
  1908. self.all_objects_list = []
  1909. # List to store the objects that are selected
  1910. self.sel_objects_list = []
  1911. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1912. self.key_modifiers = None
  1913. # Variable to hold the status of the axis
  1914. self.toggle_axis = True
  1915. # Variable to store the status of the fullscreen event
  1916. self.toggle_fscreen = False
  1917. # Variable to store the status of the code editor
  1918. self.toggle_codeeditor = False
  1919. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1920. self.click_noproject = False
  1921. self.cursor = None
  1922. # Variable to store the GCODE that was edited
  1923. self.gcode_edited = ""
  1924. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  1925. self.preferences_changed_flag = False
  1926. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3',
  1927. 'gko', 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15',
  1928. 'dim', 'mil', 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo',
  1929. 'art', 'gbd', 'gb0', 'gb1', 'gb2', 'gb3', 'g4', 'gb5', 'gb6', 'gb7', 'gb8', 'gb9'
  1930. ]
  1931. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc', 'ncd']
  1932. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1933. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1934. 'mpf'
  1935. ]
  1936. self.svg_list = ['svg']
  1937. self.dxf_list = ['dxf']
  1938. self.pdf_list = ['pdf']
  1939. self.prj_list = ['flatprj']
  1940. self.conf_list = ['flatconfig']
  1941. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1942. # flag for polygons not cleared
  1943. self.poly_not_cleared = False
  1944. # VisPy visuals
  1945. self.isHovering = False
  1946. self.notHovering = True
  1947. # when True, the app has to return from any thread
  1948. self.abort_flag = False
  1949. # ###############################################################################
  1950. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  1951. # ############# It's done only once after install ###############
  1952. # ###############################################################################
  1953. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1954. fac_def_from_file = factory_file.read()
  1955. factory_defaults = json.loads(fac_def_from_file)
  1956. # if the file contain an empty dictionary then save the factory defaults into the file
  1957. if not factory_defaults:
  1958. self.save_factory_defaults(silent=False)
  1959. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1960. initial_lay = 'compact'
  1961. self.on_layout(lay=initial_lay)
  1962. # Set the combobox in Preferences to the current layout
  1963. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  1964. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  1965. factory_file.close()
  1966. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1967. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1968. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1969. # after the first run, this object should be False
  1970. self.defaults["first_run"] = False
  1971. # ###############################################################################
  1972. # ################# ADDING FlatCAM EDITORS section ##############################
  1973. # ###############################################################################
  1974. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1975. # at the first launch of the App , the editors will not be functional.
  1976. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  1977. self.exc_editor = FlatCAMExcEditor(self)
  1978. self.grb_editor = FlatCAMGrbEditor(self)
  1979. self.log.debug("Finished adding FlatCAM Editor's.")
  1980. self.set_ui_title(name=_("New Project - Not saved"))
  1981. # finish the splash
  1982. # splash.finish(self.ui)
  1983. # ###############################################################################
  1984. # ####################### Finished the CONSTRUCTOR ##############################
  1985. # ###############################################################################
  1986. App.log.debug("END of constructor. Releasing control.")
  1987. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1988. # the path/file_name must be enclosed in quotes if it contain spaces
  1989. if App.args:
  1990. self.args_at_startup.emit(App.args)
  1991. @staticmethod
  1992. def copy_and_overwrite(from_path, to_path):
  1993. """
  1994. From here:
  1995. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1996. :param from_path: source path
  1997. :param to_path: destination path
  1998. :return: None
  1999. """
  2000. if os.path.exists(to_path):
  2001. shutil.rmtree(to_path)
  2002. try:
  2003. shutil.copytree(from_path, to_path)
  2004. except FileNotFoundError:
  2005. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2006. shutil.copytree(from_new_path, to_path)
  2007. def on_startup_args(self, args=None):
  2008. """
  2009. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2010. :param args: a list containing the application args at startup
  2011. :return: None
  2012. """
  2013. if args:
  2014. args_to_process = args
  2015. else:
  2016. args_to_process = App.args
  2017. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2018. for argument in args_to_process:
  2019. if '.FlatPrj' in argument:
  2020. try:
  2021. project_name = str(argument)
  2022. if project_name == "":
  2023. self.inform.emit(_("Open cancelled."))
  2024. else:
  2025. # self.open_project(project_name)
  2026. run_from_arg = True
  2027. # self.worker_task.emit({'fcn': self.open_project,
  2028. # 'params': [project_name, run_from_arg]})
  2029. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2030. except Exception as e:
  2031. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2032. elif '.FlatConfig' in argument:
  2033. try:
  2034. file_name = str(argument)
  2035. if file_name == "":
  2036. self.inform.emit(_("Open Config file failed."))
  2037. else:
  2038. # run_from_arg = True
  2039. # self.worker_task.emit({'fcn': self.open_config_file,
  2040. # 'params': [file_name, run_from_arg]})
  2041. self.open_config_file(file_name, run_from_arg=True)
  2042. except Exception as e:
  2043. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2044. elif '.FlatScript' in argument:
  2045. try:
  2046. file_name = str(argument)
  2047. if file_name == "":
  2048. self.inform.emit(_("Open Script file failed."))
  2049. else:
  2050. # run_from_arg = True
  2051. # self.worker_task.emit({'fcn': self.open_script_file,
  2052. # 'params': [file_name, run_from_arg]})
  2053. self.on_filerunscript(name=file_name)
  2054. except Exception as e:
  2055. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2056. else:
  2057. exc_list = self.ui.fa_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2058. proc_arg = argument.lower()
  2059. for ext in exc_list:
  2060. proc_ext = ext.replace(' ', '')
  2061. if proc_ext.lower() in proc_arg and proc_ext != '':
  2062. file_name = str(argument)
  2063. if file_name == "":
  2064. self.inform.emit(_("Open Excellon file failed."))
  2065. else:
  2066. self.on_fileopenexcellon(name=file_name)
  2067. return
  2068. gco_list = self.ui.fa_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2069. for ext in gco_list:
  2070. proc_ext = ext.replace(' ', '')
  2071. if proc_ext.lower() in proc_arg and proc_ext != '':
  2072. file_name = str(argument)
  2073. if file_name == "":
  2074. self.inform.emit(_("Open GCode file failed."))
  2075. else:
  2076. self.on_fileopengcode(name=file_name)
  2077. return
  2078. grb_list = self.ui.fa_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2079. for ext in grb_list:
  2080. proc_ext = ext.replace(' ', '')
  2081. if proc_ext.lower() in proc_arg and proc_ext != '':
  2082. file_name = str(argument)
  2083. if file_name == "":
  2084. self.inform.emit(_("Open Gerber file failed."))
  2085. else:
  2086. self.on_fileopengerber(name=file_name)
  2087. return
  2088. def set_ui_title(self, name):
  2089. """
  2090. Sets the title of the main window.
  2091. :param name: String that store the project path and project name
  2092. :return: None
  2093. """
  2094. self.ui.setWindowTitle('FlatCAM %s %s - %s %s' %
  2095. (self.version,
  2096. ('BETA' if self.beta else ''),
  2097. platform.architecture()[0],
  2098. name)
  2099. )
  2100. def defaults_read_form(self):
  2101. """
  2102. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2103. :return: None
  2104. """
  2105. for option in self.defaults_form_fields:
  2106. try:
  2107. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2108. except Exception as e:
  2109. log.debug("App.defaults_read_form() --> %s" % str(e))
  2110. def defaults_write_form(self, factor=None, fl_units=None):
  2111. """
  2112. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2113. self.defaults dictionary.
  2114. :param factor: will apply a factor to the values that written in the GUI elements
  2115. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2116. :return: None
  2117. """
  2118. for option in self.defaults:
  2119. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2120. # try:
  2121. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2122. # except KeyError:
  2123. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2124. # # TODO: Rethink this?
  2125. # pass
  2126. def defaults_write_form_field(self, field, factor=None, units=None):
  2127. """
  2128. Basically it is the worker in the self.defaults_write_form()
  2129. :param field: the GUI element in Preferences GUI to be updated
  2130. :param factor: factor to be applied to the field parameter
  2131. :param units: current FLatCAM measuring units
  2132. :return: None, it updates GUI elements
  2133. """
  2134. try:
  2135. if factor is None:
  2136. if units is None:
  2137. self.defaults_form_fields[field].set_value(self.defaults[field])
  2138. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2139. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  2140. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2141. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  2142. else:
  2143. if units is None:
  2144. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2145. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2146. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  2147. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2148. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  2149. except KeyError:
  2150. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2151. # TODO: Rethink this?
  2152. pass
  2153. except AttributeError:
  2154. log.debug(field)
  2155. def clear_pool(self):
  2156. """
  2157. Clear the multiprocessing pool and calls garbage collector.
  2158. :return: None
  2159. """
  2160. self.pool.close()
  2161. self.pool = Pool()
  2162. self.pool_recreated.emit(self.pool)
  2163. gc.collect()
  2164. def install_tools(self):
  2165. """
  2166. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2167. Instantiation of the Tools classes.
  2168. The order that the tools are installed is important as they can depend on each other install position.
  2169. :return: None
  2170. """
  2171. self.dblsidedtool = DblSidedTool(self)
  2172. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2173. self.measurement_tool = Measurement(self)
  2174. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  2175. self.panelize_tool = Panelize(self)
  2176. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  2177. self.film_tool = Film(self)
  2178. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2179. self.paste_tool = SolderPaste(self)
  2180. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2181. self.calculator_tool = ToolCalculator(self)
  2182. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'), separator=True)
  2183. self.sub_tool = ToolSub(self)
  2184. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2185. self.move_tool = ToolMove(self)
  2186. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2187. before=self.ui.menueditorigin)
  2188. self.cutout_tool = CutOut(self)
  2189. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2190. before=self.measurement_tool.menuAction)
  2191. self.ncclear_tool = NonCopperClear(self)
  2192. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2193. before=self.measurement_tool.menuAction, separator=True)
  2194. self.paint_tool = ToolPaint(self)
  2195. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2196. before=self.measurement_tool.menuAction, separator=True)
  2197. self.transform_tool = ToolTransform(self)
  2198. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2199. self.properties_tool = Properties(self)
  2200. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2201. self.pdf_tool = ToolPDF(self)
  2202. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2203. separator=True)
  2204. self.image_tool = ToolImage(self)
  2205. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2206. separator=True)
  2207. self.pcb_wizard_tool = PcbWizard(self)
  2208. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2209. self.log.debug("Tools are installed.")
  2210. def remove_tools(self):
  2211. """
  2212. Will remove all the actions in the Tool menu.
  2213. :return: None
  2214. """
  2215. for act in self.ui.menutool.actions():
  2216. self.ui.menutool.removeAction(act)
  2217. def init_tools(self):
  2218. """
  2219. Initialize the Tool tab in the notebook side of the central widget.
  2220. Remove the actions in the Tools menu.
  2221. Instantiate again the FlatCAM tools (plugins).
  2222. All this is required when changing the layout: standard, compact etc.
  2223. :return: None
  2224. """
  2225. log.debug("init_tools()")
  2226. # delete the data currently in the Tools Tab and the Tab itself
  2227. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2228. if widget is not None:
  2229. widget.deleteLater()
  2230. self.ui.notebook.removeTab(2)
  2231. # rebuild the Tools Tab
  2232. self.ui.tool_tab = QtWidgets.QWidget()
  2233. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2234. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2235. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2236. self.ui.tool_scroll_area = VerticalScrollArea()
  2237. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2238. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2239. # first remove all of them
  2240. self.remove_tools()
  2241. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2242. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2243. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2244. # third install all of them
  2245. self.install_tools()
  2246. self.log.debug("Tools are initialized.")
  2247. # def parse_system_fonts(self):
  2248. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2249. # 'params': []})
  2250. def connect_toolbar_signals(self):
  2251. """
  2252. Reconnect the signals to the actions in the toolbar.
  2253. This has to be done each time after the FlatCAM tools are removed/installed.
  2254. :return: None
  2255. """
  2256. # Toolbar
  2257. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2258. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2259. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2260. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2261. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2262. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2263. self.ui.replot_btn.triggered.connect(self.plot_all)
  2264. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2265. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2266. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2267. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2268. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2269. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2270. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2271. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2272. self.ui.delete_btn.triggered.connect(self.on_delete)
  2273. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2274. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2275. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2276. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2277. # Tools Toolbar Signals
  2278. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2279. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2280. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2281. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2282. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2283. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2284. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2285. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2286. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2287. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2288. def object2editor(self):
  2289. """
  2290. Send the current Geometry or Excellon object (if any) into the it's editor.
  2291. :return: None
  2292. """
  2293. self.report_usage("object2editor()")
  2294. edited_object = self.collection.get_active()
  2295. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2296. isinstance(edited_object, FlatCAMExcellon):
  2297. pass
  2298. else:
  2299. self.inform.emit('[WARNING_NOTCL] %s' %
  2300. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2301. return
  2302. if isinstance(edited_object, FlatCAMGeometry):
  2303. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2304. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2305. # we set the notebook to hidden
  2306. self.ui.splitter.setSizes([0, 1])
  2307. if edited_object.multigeo is True:
  2308. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2309. if len(edited_tools) > 1:
  2310. self.inform.emit('[WARNING_NOTCL] %s' %
  2311. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2312. "is not possible.\n"
  2313. "Edit only one geometry at a time."))
  2314. # determine the tool dia of the selected tool
  2315. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2316. # now find the key in the edited_object.tools that has this tooldia
  2317. multi_tool = 1
  2318. for tool in edited_object.tools:
  2319. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2320. multi_tool = tool
  2321. break
  2322. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2323. else:
  2324. self.geo_editor.edit_fcgeometry(edited_object)
  2325. # set call source to the Editor we go into
  2326. self.call_source = 'geo_editor'
  2327. elif isinstance(edited_object, FlatCAMExcellon):
  2328. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2329. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2330. if self.ui.splitter.sizes()[0] == 0:
  2331. self.ui.splitter.setSizes([1, 1])
  2332. self.exc_editor.edit_fcexcellon(edited_object)
  2333. # set call source to the Editor we go into
  2334. self.call_source = 'exc_editor'
  2335. elif isinstance(edited_object, FlatCAMGerber):
  2336. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2337. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2338. if self.ui.splitter.sizes()[0] == 0:
  2339. self.ui.splitter.setSizes([1, 1])
  2340. self.grb_editor.edit_fcgerber(edited_object)
  2341. # set call source to the Editor we go into
  2342. self.call_source = 'grb_editor'
  2343. # make sure that we can't select another object while in Editor Mode:
  2344. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2345. self.ui.project_frame.setDisabled(True)
  2346. # delete any selection shape that might be active as they are not relevant in Editor
  2347. self.delete_selection_shape()
  2348. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2349. self.ui.plot_tab_area.protectTab(0)
  2350. self.inform.emit('[WARNING_NOTCL] %s' %
  2351. _("Editor is activated ..."))
  2352. self.should_we_save = True
  2353. def editor2object(self, cleanup=None):
  2354. """
  2355. Transfers the Geometry or Excellon from it's editor to the current object.
  2356. :return: None
  2357. """
  2358. self.report_usage("editor2object()")
  2359. # do not update a geometry or excellon object unless it comes out of an editor
  2360. if self.call_source != 'app':
  2361. edited_obj = self.collection.get_active()
  2362. if cleanup is None:
  2363. msgbox = QtWidgets.QMessageBox()
  2364. msgbox.setText(_("Do you want to save the edited object?"))
  2365. msgbox.setWindowTitle(_("Close Editor"))
  2366. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2367. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2368. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2369. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2370. msgbox.setDefaultButton(bt_yes)
  2371. msgbox.exec_()
  2372. response = msgbox.clickedButton()
  2373. if response == bt_yes:
  2374. # clean the Tools Tab
  2375. self.ui.tool_scroll_area.takeWidget()
  2376. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2377. self.ui.notebook.setTabText(2, "Tool")
  2378. if isinstance(edited_obj, FlatCAMGeometry):
  2379. obj_type = "Geometry"
  2380. if cleanup is None:
  2381. self.geo_editor.update_fcgeometry(edited_obj)
  2382. self.geo_editor.update_options(edited_obj)
  2383. self.geo_editor.deactivate()
  2384. # update the geo object options so it is including the bounding box values
  2385. try:
  2386. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2387. edited_obj.options['xmin'] = xmin
  2388. edited_obj.options['ymin'] = ymin
  2389. edited_obj.options['xmax'] = xmax
  2390. edited_obj.options['ymax'] = ymax
  2391. except AttributeError as e:
  2392. self.inform.emit('[WARNING] %s' %
  2393. _("Object empty after edit."))
  2394. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2395. elif isinstance(edited_obj, FlatCAMGerber):
  2396. obj_type = "Gerber"
  2397. if cleanup is None:
  2398. self.grb_editor.update_fcgerber()
  2399. self.grb_editor.update_options(edited_obj)
  2400. self.grb_editor.deactivate_grb_editor()
  2401. # delete the old object (the source object) if it was an empty one
  2402. if len(edited_obj.solid_geometry) == 0:
  2403. old_name = edited_obj.options['name']
  2404. self.collection.set_active(old_name)
  2405. self.collection.delete_active()
  2406. elif isinstance(edited_obj, FlatCAMExcellon):
  2407. obj_type = "Excellon"
  2408. if cleanup is None:
  2409. self.exc_editor.update_fcexcellon(edited_obj)
  2410. self.exc_editor.update_options(edited_obj)
  2411. self.exc_editor.deactivate()
  2412. else:
  2413. self.inform.emit('[WARNING_NOTCL] %s' %
  2414. _("Select a Gerber, Geometry or Excellon Object to update."))
  2415. return
  2416. self.inform.emit('[selected] %s %s' %
  2417. (obj_type, _("is updated, returning to App...")))
  2418. elif response == bt_no:
  2419. # clean the Tools Tab
  2420. self.ui.tool_scroll_area.takeWidget()
  2421. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2422. self.ui.notebook.setTabText(2, "Tool")
  2423. if isinstance(edited_obj, FlatCAMGeometry):
  2424. self.geo_editor.deactivate()
  2425. elif isinstance(edited_obj, FlatCAMGerber):
  2426. self.grb_editor.deactivate_grb_editor()
  2427. elif isinstance(edited_obj, FlatCAMExcellon):
  2428. self.exc_editor.deactivate()
  2429. # set focus on the project tab
  2430. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  2431. else:
  2432. self.inform.emit('[WARNING_NOTCL] %s' %
  2433. _("Select a Gerber, Geometry or Excellon Object to update."))
  2434. return
  2435. elif response == bt_cancel:
  2436. return
  2437. else:
  2438. if isinstance(edited_obj, FlatCAMGeometry):
  2439. self.geo_editor.deactivate()
  2440. elif isinstance(edited_obj, FlatCAMGerber):
  2441. self.grb_editor.deactivate_grb_editor()
  2442. elif isinstance(edited_obj, FlatCAMExcellon):
  2443. self.exc_editor.deactivate()
  2444. else:
  2445. self.inform.emit('[WARNING_NOTCL] %s' %
  2446. _("Select a Gerber, Geometry or Excellon Object to update."))
  2447. return
  2448. # if notebook is hidden we show it
  2449. if self.ui.splitter.sizes()[0] == 0:
  2450. self.ui.splitter.setSizes([1, 1])
  2451. # restore the call_source to app
  2452. self.call_source = 'app'
  2453. edited_obj.plot()
  2454. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2455. self.ui.plot_tab_area.protectTab(0)
  2456. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2457. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2458. self.ui.project_frame.setDisabled(False)
  2459. def get_last_folder(self):
  2460. """
  2461. Get the folder path from where the last file was opened.
  2462. :return: String, last opened folder path
  2463. """
  2464. return self.defaults["global_last_folder"]
  2465. def get_last_save_folder(self):
  2466. """
  2467. Get the folder path from where the last file was saved.
  2468. :return: String, last saved folder path
  2469. """
  2470. loc = self.defaults["global_last_save_folder"]
  2471. if loc is None:
  2472. loc = self.defaults["global_last_folder"]
  2473. if loc is None:
  2474. loc = os.path.dirname(__file__)
  2475. return loc
  2476. def report_usage(self, resource):
  2477. """
  2478. Increments usage counter for the given resource
  2479. in self.defaults['global_stats'].
  2480. :param resource: Name of the resource.
  2481. :return: None
  2482. """
  2483. if resource in self.defaults['global_stats']:
  2484. self.defaults['global_stats'][resource] += 1
  2485. else:
  2486. self.defaults['global_stats'][resource] = 1
  2487. def init_tcl(self):
  2488. """
  2489. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2490. :return: None
  2491. """
  2492. if hasattr(self, 'tcl'):
  2493. # self.tcl = None
  2494. # TODO we need to clean non default variables and procedures here
  2495. # new object cannot be used here as it will not remember values created for next passes,
  2496. # because tcl was execudted in old instance of TCL
  2497. pass
  2498. else:
  2499. self.tcl = tk.Tcl()
  2500. self.setup_shell()
  2501. self.log.debug("TCL Shell has been initialized.")
  2502. # TODO: This shouldn't be here.
  2503. class TclErrorException(Exception):
  2504. """
  2505. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2506. """
  2507. pass
  2508. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2509. """
  2510. Shows a message on the FlatCAM Shell
  2511. :param msg: Message to display.
  2512. :param show: Opens the shell.
  2513. :param error: Shows the message as an error.
  2514. :param warning: Shows the message as an warning.
  2515. :param success: Shows the message as an success.
  2516. :param selected: Indicate that something was selected on canvas
  2517. :return: None
  2518. """
  2519. if show:
  2520. self.ui.shell_dock.show()
  2521. try:
  2522. if error:
  2523. self.shell.append_error(msg + "\n")
  2524. elif warning:
  2525. self.shell.append_warning(msg + "\n")
  2526. elif success:
  2527. self.shell.append_success(msg + "\n")
  2528. elif selected:
  2529. self.shell.append_selected(msg + "\n")
  2530. else:
  2531. self.shell.append_output(msg + "\n")
  2532. except AttributeError:
  2533. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2534. def raise_tcl_unknown_error(self, unknownException):
  2535. """
  2536. Raise exception if is different type than TclErrorException
  2537. this is here mainly to show unknown errors inside TCL shell console.
  2538. :param unknownException:
  2539. :return:
  2540. """
  2541. if not isinstance(unknownException, self.TclErrorException):
  2542. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2543. else:
  2544. raise unknownException
  2545. def display_tcl_error(self, error, error_info=None):
  2546. """
  2547. Escape bracket [ with '\' otherwise there is error
  2548. "ERROR: missing close-bracket" instead of real error
  2549. :param error: it may be text or exception
  2550. :param error_info: Some informations about the error
  2551. :return: None
  2552. """
  2553. if isinstance(error, Exception):
  2554. exc_type, exc_value, exc_traceback = error_info
  2555. if not isinstance(error, self.TclErrorException):
  2556. show_trace = 1
  2557. else:
  2558. show_trace = int(self.defaults['global_verbose_error_level'])
  2559. if show_trace > 0:
  2560. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2561. trc_formated = []
  2562. for a in reversed(trc):
  2563. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2564. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2565. else:
  2566. text = "%s" % error
  2567. else:
  2568. text = error
  2569. text = text.replace('[', '\\[').replace('"', '\\"')
  2570. self.tcl.eval('return -code error "%s"' % text)
  2571. def raise_tcl_error(self, text):
  2572. """
  2573. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2574. :param text: text of error
  2575. :return: raise exception
  2576. """
  2577. self.display_tcl_error(text)
  2578. raise self.TclErrorException(text)
  2579. def exec_command(self, text, no_plot=None):
  2580. """
  2581. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2582. Also handles execution in separated threads
  2583. :param text: FlatCAM TclCommand with parameters
  2584. :return: output if there was any
  2585. """
  2586. self.report_usage('exec_command')
  2587. result = self.exec_command_test(text, False)
  2588. # MS: added this method call so the geometry is updated once the TCL command is executed
  2589. if no_plot is None:
  2590. self.plot_all()
  2591. return result
  2592. def exec_command_test(self, text, reraise=True):
  2593. """
  2594. Same as exec_command(...) with additional control over exceptions.
  2595. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2596. :param text: Input command
  2597. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2598. :return: Output from the command
  2599. """
  2600. tcl_command_string = str(text)
  2601. try:
  2602. self.shell.open_proccessing() # Disables input box.
  2603. result = self.tcl.eval(str(tcl_command_string))
  2604. if result != 'None':
  2605. self.shell.append_output(result + '\n')
  2606. except tk.TclError as e:
  2607. # This will display more precise answer if something in TCL shell fails
  2608. result = self.tcl.eval("set errorInfo")
  2609. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2610. self.shell.append_error('ERROR: ' + result + '\n')
  2611. # Show error in console and just return or in test raise exception
  2612. if reraise:
  2613. raise e
  2614. finally:
  2615. self.shell.close_proccessing()
  2616. pass
  2617. return result
  2618. # """
  2619. # Code below is unsused. Saved for later.
  2620. # """
  2621. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2622. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2623. # self.log.debug(parts)
  2624. # try:
  2625. # if parts[0] not in commands:
  2626. # self.shell.append_error("Unknown command\n")
  2627. # return
  2628. #
  2629. # #import inspect
  2630. # #inspect.getargspec(someMethod)
  2631. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2632. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2633. # self.shell.append_error(
  2634. # "Command %s takes %d arguments. %d given.\n" %
  2635. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2636. # )
  2637. # return
  2638. #
  2639. # cmdfcn = commands[parts[0]]["fcn"]
  2640. # cmdconv = commands[parts[0]]["converters"]
  2641. # if len(parts) - 1 > 0:
  2642. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2643. # else:
  2644. # retval = cmdfcn()
  2645. # retfcn = commands[parts[0]]["retfcn"]
  2646. # if retval and retfcn(retval):
  2647. # self.shell.append_output(retfcn(retval) + "\n")
  2648. #
  2649. # except Exception as e:
  2650. # #self.shell.append_error(''.join(traceback.format_exc()))
  2651. # #self.shell.append_error("?\n")
  2652. # self.shell.append_error(str(e) + "\n")
  2653. def info(self, msg):
  2654. """
  2655. Informs the user. Normally on the status bar, optionally
  2656. also on the shell.
  2657. :param msg: Text to write.
  2658. :return: None
  2659. """
  2660. # Type of message in brackets at the beginning of the message.
  2661. match = re.search("\[([^\]]+)\](.*)", msg)
  2662. if match:
  2663. level = match.group(1)
  2664. msg_ = match.group(2)
  2665. self.ui.fcinfo.set_status(str(msg_), level=level)
  2666. if level.lower() == "error":
  2667. self.shell_message(msg, error=True, show=True)
  2668. elif level.lower() == "warning":
  2669. self.shell_message(msg, warning=True, show=True)
  2670. elif level.lower() == "error_notcl":
  2671. self.shell_message(msg, error=True, show=False)
  2672. elif level.lower() == "warning_notcl":
  2673. self.shell_message(msg, warning=True, show=False)
  2674. elif level.lower() == "success":
  2675. self.shell_message(msg, success=True, show=False)
  2676. elif level.lower() == "selected":
  2677. self.shell_message(msg, selected=True, show=False)
  2678. else:
  2679. self.shell_message(msg, show=False)
  2680. else:
  2681. self.ui.fcinfo.set_status(str(msg), level="info")
  2682. # make sure that if the message is to clear the infobar with a space
  2683. # is not printed over and over on the shell
  2684. if msg != '':
  2685. self.shell_message(msg)
  2686. def restore_toolbar_view(self):
  2687. """
  2688. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  2689. was saved in the defaults dictionary.
  2690. :return: None
  2691. """
  2692. tb = self.defaults["global_toolbar_view"]
  2693. if tb & 1:
  2694. self.ui.toolbarfile.setVisible(True)
  2695. else:
  2696. self.ui.toolbarfile.setVisible(False)
  2697. if tb & 2:
  2698. self.ui.toolbargeo.setVisible(True)
  2699. else:
  2700. self.ui.toolbargeo.setVisible(False)
  2701. if tb & 4:
  2702. self.ui.toolbarview.setVisible(True)
  2703. else:
  2704. self.ui.toolbarview.setVisible(False)
  2705. if tb & 8:
  2706. self.ui.toolbartools.setVisible(True)
  2707. else:
  2708. self.ui.toolbartools.setVisible(False)
  2709. if tb & 16:
  2710. self.ui.exc_edit_toolbar.setVisible(True)
  2711. else:
  2712. self.ui.exc_edit_toolbar.setVisible(False)
  2713. if tb & 32:
  2714. self.ui.geo_edit_toolbar.setVisible(True)
  2715. else:
  2716. self.ui.geo_edit_toolbar.setVisible(False)
  2717. if tb & 64:
  2718. self.ui.grb_edit_toolbar.setVisible(True)
  2719. else:
  2720. self.ui.grb_edit_toolbar.setVisible(False)
  2721. if tb & 128:
  2722. self.ui.snap_toolbar.setVisible(True)
  2723. else:
  2724. self.ui.snap_toolbar.setVisible(False)
  2725. if tb & 256:
  2726. self.ui.toolbarshell.setVisible(True)
  2727. else:
  2728. self.ui.toolbarshell.setVisible(False)
  2729. def load_defaults(self, filename):
  2730. """
  2731. Loads the aplication's default settings from current_defaults.FlatConfig into
  2732. ``self.defaults``.
  2733. :return: None
  2734. """
  2735. try:
  2736. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2737. options = f.read()
  2738. f.close()
  2739. except IOError:
  2740. self.log.error("Could not load defaults file.")
  2741. self.inform.emit('[ERROR] %s' %
  2742. _("Could not load defaults file."))
  2743. # in case the defaults file can't be loaded, show all toolbars
  2744. self.defaults["global_toolbar_view"] = 511
  2745. return
  2746. try:
  2747. defaults = json.loads(options)
  2748. except:
  2749. # in case the defaults file can't be loaded, show all toolbars
  2750. self.defaults["global_toolbar_view"] = 511
  2751. e = sys.exc_info()[0]
  2752. App.log.error(str(e))
  2753. self.inform.emit('[ERROR] %s' %
  2754. _("Failed to parse defaults file."))
  2755. return
  2756. self.defaults.update(defaults)
  2757. log.debug("FlatCAM defaults loaded from: %s" % filename)
  2758. # restore the toolbar view
  2759. self.restore_toolbar_view()
  2760. def on_import_preferences(self):
  2761. """
  2762. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  2763. ``self.defaults``.
  2764. :return: None
  2765. """
  2766. self.report_usage("on_import_preferences")
  2767. App.log.debug("on_import_preferences()")
  2768. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2769. try:
  2770. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2771. directory=self.data_path,
  2772. filter=filter_)
  2773. except TypeError:
  2774. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2775. filter=filter_)
  2776. filename = str(filename)
  2777. if filename == "":
  2778. self.inform.emit('[WARNING_NOTCL] %s' %
  2779. _("FlatCAM preferences import cancelled."))
  2780. else:
  2781. try:
  2782. f = open(filename)
  2783. options = f.read()
  2784. f.close()
  2785. except IOError:
  2786. self.log.error("Could not load defaults file.")
  2787. self.inform.emit('[ERROR_NOTCL] %s' %
  2788. _("Could not load defaults file."))
  2789. return
  2790. try:
  2791. defaults_from_file = json.loads(options)
  2792. except Exception as e:
  2793. e = sys.exc_info()[0]
  2794. App.log.error(str(e))
  2795. self.inform.emit('[ERROR_NOTCL] %s' %
  2796. _("Failed to parse defaults file."))
  2797. return
  2798. self.defaults.update(defaults_from_file)
  2799. self.on_preferences_edited()
  2800. self.inform.emit('[success] %s: %s' %
  2801. (_("Imported Defaults from"), filename))
  2802. def on_export_preferences(self):
  2803. """
  2804. Save the defaults dictionary to a file.
  2805. :return: None
  2806. """
  2807. self.report_usage("on_export_preferences")
  2808. App.log.debug("on_export_preferences()")
  2809. defaults_file_content = None
  2810. self.date = str(datetime.today()).rpartition('.')[0]
  2811. self.date = ''.join(c for c in self.date if c not in ':-')
  2812. self.date = self.date.replace(' ', '_')
  2813. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  2814. try:
  2815. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  2816. caption=_("Export FlatCAM Preferences"),
  2817. directory=self.data_path + '/preferences_' + self.date,
  2818. filter=filter__
  2819. )
  2820. except TypeError:
  2821. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  2822. filter=filter__)
  2823. filename = str(filename)
  2824. defaults_from_file = {}
  2825. if filename == "":
  2826. self.inform.emit('[WARNING_NOTCL] %s' %
  2827. _("FlatCAM preferences export cancelled."))
  2828. return
  2829. else:
  2830. try:
  2831. f = open(filename, 'w')
  2832. defaults_file_content = f.read()
  2833. f.close()
  2834. except PermissionError:
  2835. self.inform.emit('[WARNING] %s' %
  2836. _("Permission denied, saving not possible.\n"
  2837. "Most likely another app is holding the file open and not accessible."))
  2838. return
  2839. except IOError:
  2840. App.log.debug('Creating a new preferences file ...')
  2841. f = open(filename, 'w')
  2842. json.dump({}, f)
  2843. f.close()
  2844. except:
  2845. e = sys.exc_info()[0]
  2846. App.log.error("Could not load defaults file.")
  2847. App.log.error(str(e))
  2848. self.inform.emit('[ERROR_NOTCL] %s' %
  2849. _("Could not load preferences file."))
  2850. return
  2851. try:
  2852. defaults_from_file = json.loads(defaults_file_content)
  2853. except:
  2854. App.log.warning("Trying to read an empty Preferences file. Continue.")
  2855. # Update options
  2856. self.defaults_read_form()
  2857. defaults_from_file.update(self.defaults)
  2858. self.propagate_defaults(silent=True)
  2859. # Save update options
  2860. try:
  2861. f = open(filename, "w")
  2862. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  2863. f.close()
  2864. except:
  2865. self.inform.emit('[ERROR_NOTCL] %s' %
  2866. _("Failed to write defaults to file."))
  2867. return
  2868. if self.defaults["global_open_style"] is False:
  2869. self.file_opened.emit("preferences", filename)
  2870. self.file_saved.emit("preferences", filename)
  2871. self.inform.emit('[success] %s: %s' %
  2872. (_("Exported preferences to"), filename))
  2873. def on_preferences_open_folder(self):
  2874. """
  2875. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  2876. :return: None
  2877. """
  2878. self.report_usage("on_preferences_open_folder()")
  2879. if sys.platform == 'win32':
  2880. subprocess.Popen('explorer %s' % self.data_path)
  2881. elif sys.platform == 'darwin':
  2882. os.system('open "%s"' % self.data_path)
  2883. else:
  2884. subprocess.Popen(['xdg-open', self.data_path])
  2885. self.inform.emit('[success] %s' %
  2886. _("FlatCAM Preferences Folder opened."))
  2887. def save_geometry(self, x, y, width, height, notebook_width):
  2888. """
  2889. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2890. launch of the application.
  2891. :param x: X position of the main window
  2892. :param y: Y position of the main window
  2893. :param width: width of the main window
  2894. :param height: height of the main window
  2895. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2896. :return: None
  2897. """
  2898. self.defaults["global_def_win_x"] = x
  2899. self.defaults["global_def_win_y"] = y
  2900. self.defaults["global_def_win_w"] = width
  2901. self.defaults["global_def_win_h"] = height
  2902. self.defaults["global_def_notebook_width"] = notebook_width
  2903. self.save_defaults()
  2904. def message_dialog(self, title, message, kind="info"):
  2905. """
  2906. Builds and show a custom QMessageBox to be used in FlatCAM.
  2907. :param title: title of the QMessageBox
  2908. :param message: message to be displayed
  2909. :param kind: type of QMessageBox; will display a specific icon.
  2910. :return:
  2911. """
  2912. icon = {"info": QtWidgets.QMessageBox.Information,
  2913. "warning": QtWidgets.QMessageBox.Warning,
  2914. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2915. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2916. dlg.setText(message)
  2917. dlg.exec_()
  2918. def register_recent(self, kind, filename):
  2919. """
  2920. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2921. dictionary.
  2922. :param kind: type of file that was opened
  2923. :param filename: the path and file name for the file that was opened
  2924. :return:
  2925. """
  2926. self.log.debug("register_recent()")
  2927. self.log.debug(" %s" % kind)
  2928. self.log.debug(" %s" % filename)
  2929. record = {'kind': str(kind), 'filename': str(filename)}
  2930. if record in self.recent:
  2931. return
  2932. if record in self.recent_projects:
  2933. return
  2934. if record['kind'] == 'project':
  2935. self.recent_projects.insert(0, record)
  2936. else:
  2937. self.recent.insert(0, record)
  2938. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2939. self.recent.pop()
  2940. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2941. self.recent_projects.pop()
  2942. try:
  2943. f = open(self.data_path + '/recent.json', 'w')
  2944. except IOError:
  2945. App.log.error("Failed to open recent items file for writing.")
  2946. self.inform.emit('[ERROR_NOTCL] %s' %
  2947. _('Failed to open recent files file for writing.'))
  2948. return
  2949. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2950. f.close()
  2951. try:
  2952. fp = open(self.data_path + '/recent_projects.json', 'w')
  2953. except IOError:
  2954. App.log.error("Failed to open recent items file for writing.")
  2955. self.inform.emit('[ERROR_NOTCL] %s' %
  2956. _('Failed to open recent projects file for writing.'))
  2957. return
  2958. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2959. fp.close()
  2960. # Re-build the recent items menu
  2961. self.setup_recent_items()
  2962. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2963. """
  2964. Creates a new specialized FlatCAMObj and attaches it to the application,
  2965. this is, updates the GUI accordingly, any other records and plots it.
  2966. This method is thread-safe.
  2967. Notes:
  2968. * If the name is in use, the self.collection will modify it
  2969. when appending it to the collection. There is no need to handle
  2970. name conflicts here.
  2971. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2972. :type kind: str
  2973. :param name: Name for the object.
  2974. :type name: str
  2975. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2976. The function is called with 2 parameters: the new object and the App instance.
  2977. :type initialize: function
  2978. :param active:
  2979. :param fit:
  2980. :param plot: If to plot the resulting object
  2981. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2982. self.colleaction
  2983. :return: None
  2984. :rtype: None
  2985. """
  2986. App.log.debug("new_object()")
  2987. obj_plot = plot
  2988. obj_autoselected = autoselected
  2989. t0 = time.time() # Debug
  2990. # ## Create object
  2991. classdict = {
  2992. "gerber": FlatCAMGerber,
  2993. "excellon": FlatCAMExcellon,
  2994. "cncjob": FlatCAMCNCjob,
  2995. "geometry": FlatCAMGeometry
  2996. }
  2997. App.log.debug("Calling object constructor...")
  2998. obj = classdict[kind](name)
  2999. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3000. # Set options from "Project options" form
  3001. self.options_read_form()
  3002. # IMPORTANT
  3003. # The key names in defaults and options dictionary's are not random:
  3004. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3005. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  3006. # the options from project options form into the self.options. After that, below, depending on the type of
  3007. # object that is created, it will strip the name of the object and the underline (if the original key was
  3008. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3009. # "toolchange"
  3010. for option in self.options:
  3011. if option.find(kind + "_") == 0:
  3012. oname = option[len(kind) + 1:]
  3013. obj.options[oname] = self.options[option]
  3014. obj.isHovering = False
  3015. obj.notHovering = True
  3016. # Initialize as per user request
  3017. # User must take care to implement initialize
  3018. # in a thread-safe way as is is likely that we
  3019. # have been invoked in a separate thread.
  3020. t1 = time.time()
  3021. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3022. try:
  3023. return_value = initialize(obj, self)
  3024. except Exception as e:
  3025. msg = '[ERROR_NOTCL] %s' % \
  3026. _("An internal error has ocurred. See shell.\n")
  3027. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3028. msg += traceback.format_exc()
  3029. self.inform.emit(msg)
  3030. # if str(e) == "Empty Geometry":
  3031. # self.inform.emit("[ERROR_NOTCL] )
  3032. # else:
  3033. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3034. return "fail"
  3035. t2 = time.time()
  3036. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3037. if return_value == 'fail':
  3038. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3039. return "fail"
  3040. # Check units and convert if necessary
  3041. # This condition CAN be true because initialize() can change obj.units
  3042. if self.options["units"].upper() != obj.units.upper():
  3043. self.inform.emit('%s: %s' %
  3044. (_("Converting units to "), self.options["units"]))
  3045. obj.convert_units(self.options["units"])
  3046. t3 = time.time()
  3047. self.log.debug("%f seconds converting units." % (t3 - t2))
  3048. # Create the bounding box for the object and then add the results to the obj.options
  3049. try:
  3050. xmin, ymin, xmax, ymax = obj.bounds()
  3051. obj.options['xmin'] = xmin
  3052. obj.options['ymin'] = ymin
  3053. obj.options['xmax'] = xmax
  3054. obj.options['ymax'] = ymax
  3055. except Exception as e:
  3056. log.warning("The object has no bounds properties. %s" % str(e))
  3057. return "fail"
  3058. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3059. # Move the object to the main thread and let the app know that it is available.
  3060. obj.moveToThread(self.main_thread)
  3061. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3062. return obj
  3063. def new_excellon_object(self):
  3064. """
  3065. Creates a new, blank Excellon object.
  3066. :return: None
  3067. """
  3068. self.report_usage("new_excellon_object()")
  3069. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3070. def new_geometry_object(self):
  3071. """
  3072. Creates a new, blank and single-tool Geometry object.
  3073. :return: None
  3074. """
  3075. self.report_usage("new_geometry_object()")
  3076. def initialize(obj, self):
  3077. obj.multitool = False
  3078. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3079. def new_gerber_object(self):
  3080. """
  3081. Creates a new, blank Gerber object.
  3082. :return: None
  3083. """
  3084. self.report_usage("new_gerber_object()")
  3085. def initialize(grb_obj, self):
  3086. grb_obj.multitool = False
  3087. grb_obj.source_file = []
  3088. grb_obj.multigeo = False
  3089. grb_obj.follow = False
  3090. grb_obj.apertures = {}
  3091. grb_obj.solid_geometry = []
  3092. try:
  3093. grb_obj.options['xmin'] = 0
  3094. grb_obj.options['ymin'] = 0
  3095. grb_obj.options['xmax'] = 0
  3096. grb_obj.options['ymax'] = 0
  3097. except KeyError:
  3098. pass
  3099. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3100. def on_object_created(self, obj, plot, autoselect):
  3101. """
  3102. Event callback for object creation.
  3103. It will add the new object to the collection. After that it will plot the object in a threaded way
  3104. :param obj: The newly created FlatCAM object.
  3105. :param plot: if the newly create object t obe plotted
  3106. :param autoselect: if the newly created object to be autoselected after creation
  3107. :return: None
  3108. """
  3109. t0 = time.time() # DEBUG
  3110. self.log.debug("on_object_created()")
  3111. # The Collection might change the name if there is a collision
  3112. self.collection.append(obj)
  3113. # after adding the object to the collection always update the list of objects that are in the collection
  3114. self.all_objects_list = self.collection.get_list()
  3115. # self.inform.emit('[selected] %s created & selected: %s' %
  3116. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3117. if obj.kind == 'gerber':
  3118. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3119. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3120. elif obj.kind == 'excellon':
  3121. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3122. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3123. elif obj.kind == 'cncjob':
  3124. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3125. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3126. elif obj.kind == 'geometry':
  3127. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3128. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3129. # update the SHELL auto-completer model with the name of the new object
  3130. self.myKeywords.append(obj.options['name'])
  3131. self.shell._edit.set_model_data(self.myKeywords)
  3132. self.ui.code_editor.set_model_data(self.myKeywords)
  3133. if autoselect:
  3134. # select the just opened object but deselect the previous ones
  3135. self.collection.set_all_inactive()
  3136. self.collection.set_active(obj.options["name"])
  3137. else:
  3138. self.collection.set_all_inactive()
  3139. # here it is done the object plotting
  3140. def worker_task(t_obj):
  3141. with self.proc_container.new(_("Plotting")):
  3142. if isinstance(t_obj, FlatCAMCNCjob):
  3143. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3144. else:
  3145. t_obj.plot()
  3146. t1 = time.time() # DEBUG
  3147. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3148. self.object_plotted.emit(t_obj)
  3149. # Send to worker
  3150. # self.worker.add_task(worker_task, [self])
  3151. if plot is True:
  3152. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3153. def on_object_changed(self, obj):
  3154. """
  3155. Called whenever the geometry of the object was changed in some way.
  3156. This require the update of it's bounding values so it can be the selected on canvas.
  3157. Update the bounding box data from obj.options
  3158. :param obj: the object that was changed
  3159. :return: None
  3160. """
  3161. xmin, ymin, xmax, ymax = obj.bounds()
  3162. obj.options['xmin'] = xmin
  3163. obj.options['ymin'] = ymin
  3164. obj.options['xmax'] = xmax
  3165. obj.options['ymax'] = ymax
  3166. log.debug("Object changed, updating the bounding box data on self.options")
  3167. # delete the old selection shape
  3168. self.delete_selection_shape()
  3169. self.should_we_save = True
  3170. def on_object_plotted(self, obj):
  3171. """
  3172. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3173. :param obj: object to be fit into view
  3174. :return: None
  3175. """
  3176. self.on_zoom_fit(None)
  3177. def options_read_form(self):
  3178. """
  3179. Same as it's equivalent from the defaults.
  3180. self.options use to store the preferences per project. No longer used.
  3181. :return: None
  3182. """
  3183. for option in self.options_form_fields:
  3184. self.options[option] = self.options_form_fields[option].get_value()
  3185. def options_write_form(self):
  3186. """
  3187. Same as it's equivalent from the defaults.
  3188. self.options use to store the preferences per project. No longer used.
  3189. :return: None
  3190. """
  3191. for option in self.options:
  3192. self.options_write_form_field(option)
  3193. def options_write_form_field(self, field):
  3194. """
  3195. Same as it's equivalent from the defaults.
  3196. self.options use to store the preferences per project. No longer used.
  3197. :return: None
  3198. """
  3199. try:
  3200. self.options_form_fields[field].set_value(self.options[field])
  3201. except KeyError:
  3202. # Changed from error to debug. This allows to have data stored
  3203. # which is not user-editable.
  3204. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3205. pass
  3206. def on_about(self):
  3207. """
  3208. Displays the "about" dialog found in the Menu --> Help.
  3209. :return: None
  3210. """
  3211. self.report_usage("on_about")
  3212. version = self.version
  3213. version_date = self.version_date
  3214. beta = self.beta
  3215. class AboutDialog(QtWidgets.QDialog):
  3216. def __init__(self, parent=None):
  3217. QtWidgets.QDialog.__init__(self, parent)
  3218. # Icon and title
  3219. self.setWindowIcon(parent.app_icon)
  3220. self.setWindowTitle(_("About FlatCAM"))
  3221. self.resize(600, 200)
  3222. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3223. # self.setStyleSheet(
  3224. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3225. # "background-attachment: fixed"
  3226. # )
  3227. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3228. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3229. # palette = QtGui.QPalette()
  3230. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3231. # self.setPalette(palette)
  3232. logo = QtWidgets.QLabel()
  3233. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3234. title = QtWidgets.QLabel(
  3235. "<font size=8><B>FlatCAM</B></font><BR>"
  3236. "{title}<BR>"
  3237. "<BR>"
  3238. "<BR>"
  3239. "<B>{devel}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3240. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  3241. "<b>{down}</B> area &nbsp;&nbsp;&nbsp;&nbsp;"
  3242. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  3243. "<b> {issue}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3244. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">here.</a><BR>".
  3245. format(title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3246. devel=_("Development"), down=_("DOWNLOAD"), issue=_("Issue tracker"))
  3247. )
  3248. title.setOpenExternalLinks(True)
  3249. closebtn = QtWidgets.QPushButton(_("Close"))
  3250. tab_widget = QtWidgets.QTabWidget()
  3251. description_label = QtWidgets.QLabel(
  3252. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3253. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3254. version=version,beta=('BETA' if beta else ''),
  3255. date=version_date,
  3256. arch=platform.architecture()[0])
  3257. )
  3258. description_label.setOpenExternalLinks(True)
  3259. license_label = QtWidgets.QLabel(
  3260. _(
  3261. '(c) Copyright 2014 Juan Pablo Caram.\n\n'
  3262. 'Licensed under the MIT license:\n'
  3263. 'http://www.opensource.org/licenses/mit-license.php\n\n'
  3264. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3265. 'of this software and associated documentation files (the "Software"), to deal\n'
  3266. 'in the Software without restriction, including without limitation the rights\n'
  3267. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3268. 'copies of the Software, and to permit persons to whom the Software is\n'
  3269. ' furnished to do so, subject to the following conditions:\n\n'
  3270. 'The above copyright notice and this permission notice shall be included in\n'
  3271. 'all copies or substantial portions of the Software.\n\n'
  3272. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3273. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3274. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3275. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3276. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3277. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3278. 'THE SOFTWARE.'
  3279. )
  3280. )
  3281. license_label.setOpenExternalLinks(True)
  3282. # layouts
  3283. layout1 = QtWidgets.QVBoxLayout()
  3284. layout1_1 = QtWidgets.QHBoxLayout()
  3285. layout1_2 = QtWidgets.QHBoxLayout()
  3286. layout2 = QtWidgets.QHBoxLayout()
  3287. layout3 = QtWidgets.QHBoxLayout()
  3288. self.setLayout(layout1)
  3289. layout1.addLayout(layout1_1)
  3290. layout1.addLayout(layout1_2)
  3291. layout1.addLayout(layout2)
  3292. layout1.addLayout(layout3)
  3293. layout1_1.addStretch()
  3294. layout1_1.addWidget(description_label)
  3295. layout1_2.addWidget(tab_widget)
  3296. self.splash_tab = QtWidgets.QWidget()
  3297. self.splash_tab.setObjectName("splash_about")
  3298. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3299. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3300. tab_widget.addTab(self.splash_tab, _("Splash"))
  3301. self.programmmers_tab = QtWidgets.QWidget()
  3302. self.programmmers_tab.setObjectName("programmers_about")
  3303. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3304. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3305. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3306. self.translators_tab = QtWidgets.QWidget()
  3307. self.translators_tab.setObjectName("translators_about")
  3308. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3309. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3310. tab_widget.addTab(self.translators_tab, _("Translators"))
  3311. self.license_tab = QtWidgets.QWidget()
  3312. self.license_tab.setObjectName("license_about")
  3313. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3314. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3315. tab_widget.addTab(self.license_tab, _("License"))
  3316. self.splash_tab_layout.addWidget(logo, stretch=0)
  3317. self.splash_tab_layout.addWidget(title, stretch=1)
  3318. self.prog_grid_lay = QtWidgets.QGridLayout()
  3319. prog_widget = QtWidgets.QWidget()
  3320. prog_widget.setLayout(self.prog_grid_lay)
  3321. self.programmmers_tab_layout.addWidget(prog_widget)
  3322. self.programmmers_tab_layout.addStretch()
  3323. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  3324. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  3325. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  3326. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  3327. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  3328. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 1)
  3329. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  3330. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  3331. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  3332. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Maintainer >=2019")), 4, 1)
  3333. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 5, 0)
  3334. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 1)
  3335. self.translator_grid_lay = QtWidgets.QGridLayout()
  3336. trans_widget = QtWidgets.QWidget()
  3337. trans_widget.setLayout(self.translator_grid_lay)
  3338. self.translators_tab_layout.addWidget(trans_widget)
  3339. self.translators_tab_layout.addStretch()
  3340. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3341. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3342. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3343. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Brasilian - Portuguese"), 1, 0)
  3344. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3345. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 1, 2)
  3346. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 2, 0)
  3347. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 2, 1)
  3348. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 2)
  3349. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 3, 0)
  3350. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 3, 1)
  3351. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  3352. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 4, 0)
  3353. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 4, 1)
  3354. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 4, 2)
  3355. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 5, 0)
  3356. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 5, 1)
  3357. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 2)
  3358. self.translator_grid_lay.setColumnStretch(0, 0)
  3359. # self.translators_tab_layout.addStretch()
  3360. self.license_tab_layout.addWidget(license_label)
  3361. self.license_tab_layout.addStretch()
  3362. layout3.addStretch()
  3363. layout3.addWidget(closebtn)
  3364. closebtn.clicked.connect(self.accept)
  3365. AboutDialog(self.ui).exec_()
  3366. def on_file_savedefaults(self):
  3367. """
  3368. Callback for menu item File->Save Defaults. Saves application default options
  3369. ``self.defaults`` to current_defaults.FlatConfig.
  3370. :return: None
  3371. """
  3372. self.save_defaults()
  3373. # def on_app_exit(self):
  3374. # self.report_usage("on_app_exit()")
  3375. #
  3376. # if self.collection.get_list():
  3377. # msgbox = QtWidgets.QMessageBox()
  3378. # # msgbox.setText("<B>Save changes ...</B>")
  3379. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3380. # "\n"
  3381. # "Do you want to Save the project?")
  3382. # msgbox.setWindowTitle("Save changes")
  3383. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3384. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3385. # QtWidgets.QMessageBox.Cancel)
  3386. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3387. #
  3388. # response = msgbox.exec_()
  3389. #
  3390. # if response == QtWidgets.QMessageBox.Yes:
  3391. # self.on_file_saveprojectas(thread=False)
  3392. # elif response == QtWidgets.QMessageBox.Cancel:
  3393. # return
  3394. # self.save_defaults()
  3395. # else:
  3396. # self.save_defaults()
  3397. # log.debug("Application defaults saved ... Exit event.")
  3398. # QtWidgets.qApp.quit()
  3399. def save_defaults(self, silent=False, data_path=None):
  3400. """
  3401. Saves application default options
  3402. ``self.defaults`` to current_defaults.FlatConfig file.
  3403. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3404. used at the next launch of the application.
  3405. :param silent: whether to display a message in status bar or not; boolean
  3406. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3407. When the application is portable it should be a mobile location.
  3408. :return: None
  3409. """
  3410. self.report_usage("save_defaults")
  3411. if data_path is None:
  3412. data_path = self.data_path
  3413. # Read options from file
  3414. try:
  3415. f = open(data_path + "/current_defaults.FlatConfig")
  3416. defaults_file_content = f.read()
  3417. f.close()
  3418. except:
  3419. e = sys.exc_info()[0]
  3420. App.log.error("Could not load defaults file.")
  3421. App.log.error(str(e))
  3422. self.inform.emit('[ERROR_NOTCL] %s' %
  3423. _("Could not load defaults file."))
  3424. return
  3425. try:
  3426. defaults = json.loads(defaults_file_content)
  3427. except:
  3428. e = sys.exc_info()[0]
  3429. App.log.error("Failed to parse defaults file.")
  3430. App.log.error(str(e))
  3431. self.inform.emit('[ERROR_NOTCL] %s' %
  3432. _("Failed to parse defaults file."))
  3433. return
  3434. # Update options
  3435. self.defaults_read_form()
  3436. defaults.update(self.defaults)
  3437. self.propagate_defaults(silent=True)
  3438. # Save the toolbar view
  3439. tb_status = 0
  3440. if self.ui.toolbarfile.isVisible():
  3441. tb_status += 1
  3442. if self.ui.toolbargeo.isVisible():
  3443. tb_status += 2
  3444. if self.ui.toolbarview.isVisible():
  3445. tb_status += 4
  3446. if self.ui.toolbartools.isVisible():
  3447. tb_status += 8
  3448. if self.ui.exc_edit_toolbar.isVisible():
  3449. tb_status += 16
  3450. if self.ui.geo_edit_toolbar.isVisible():
  3451. tb_status += 32
  3452. if self.ui.grb_edit_toolbar.isVisible():
  3453. tb_status += 64
  3454. if self.ui.snap_toolbar.isVisible():
  3455. tb_status += 128
  3456. if self.ui.toolbarshell.isVisible():
  3457. tb_status += 256
  3458. self.defaults["global_toolbar_view"] = tb_status
  3459. # Save update options
  3460. try:
  3461. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3462. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3463. f.close()
  3464. except:
  3465. self.inform.emit('[ERROR_NOTCL] %s' %
  3466. _("Failed to write defaults to file."))
  3467. return
  3468. if not silent:
  3469. self.inform.emit('[success] %s' %
  3470. _("Preferences saved."))
  3471. def save_factory_defaults(self, silent=False, data_path=None):
  3472. """
  3473. Saves application factory default options
  3474. ``self.defaults`` to factory_defaults.FlatConfig.
  3475. It's a one time job done just after the first install.
  3476. :param silent: whether to display a message in status bar or not; boolean
  3477. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3478. When the application is portable it should be a mobile location.
  3479. :return: None
  3480. """
  3481. self.report_usage("save_factory_defaults")
  3482. if data_path is None:
  3483. data_path = self.data_path
  3484. # Read options from file
  3485. try:
  3486. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3487. factory_defaults_file_content = f_f_def.read()
  3488. f_f_def.close()
  3489. except:
  3490. e = sys.exc_info()[0]
  3491. App.log.error("Could not load factory defaults file.")
  3492. App.log.error(str(e))
  3493. self.inform.emit('[ERROR_NOTCL] %s' %
  3494. _("Could not load factory defaults file."))
  3495. return
  3496. try:
  3497. factory_defaults = json.loads(factory_defaults_file_content)
  3498. except:
  3499. e = sys.exc_info()[0]
  3500. App.log.error("Failed to parse factory defaults file.")
  3501. App.log.error(str(e))
  3502. self.inform.emit('[ERROR_NOTCL] %s' %
  3503. _("Failed to parse factory defaults file."))
  3504. return
  3505. # Update options
  3506. self.defaults_read_form()
  3507. factory_defaults.update(self.defaults)
  3508. self.propagate_defaults(silent=True)
  3509. # Save update options
  3510. try:
  3511. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  3512. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3513. f_f_def_s.close()
  3514. except:
  3515. self.inform.emit('[ERROR_NOTCL] %s' %
  3516. _("Failed to write factory defaults to file."))
  3517. return
  3518. if silent is False:
  3519. self.inform.emit(_("Factory defaults saved."))
  3520. def final_save(self):
  3521. """
  3522. Callback for doing a preferences save to file whenever the application is about to quit.
  3523. If the project has changes, it will ask the user to save the project.
  3524. :return: None
  3525. """
  3526. if self.save_in_progress:
  3527. self.inform.emit('[WARNING_NOTCL] %s' %
  3528. _("Application is saving the project. Please wait ..."))
  3529. return
  3530. if self.should_we_save and self.collection.get_list():
  3531. msgbox = QtWidgets.QMessageBox()
  3532. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3533. "\n"
  3534. "Do you want to Save the project?"))
  3535. msgbox.setWindowTitle(_("Save changes"))
  3536. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3537. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3538. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3539. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3540. msgbox.setDefaultButton(bt_yes)
  3541. msgbox.exec_()
  3542. response = msgbox.clickedButton()
  3543. if response == bt_yes:
  3544. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  3545. elif response == bt_no:
  3546. self.quit_application()
  3547. elif response == bt_cancel:
  3548. return
  3549. else:
  3550. self.quit_application()
  3551. def quit_application(self):
  3552. """
  3553. Called (as a pyslot or not) when the application is quit.
  3554. :return: None
  3555. """
  3556. self.save_defaults()
  3557. log.debug("App.final_save() --> App Defaults saved.")
  3558. # save toolbar state to file
  3559. settings = QSettings("Open Source", "FlatCAM")
  3560. settings.setValue('saved_gui_state', self.ui.saveState())
  3561. settings.setValue('maximized_gui', self.ui.isMaximized())
  3562. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  3563. settings.setValue('notebook_font_size',
  3564. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value())
  3565. settings.setValue('axis_font_size',
  3566. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  3567. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3568. # This will write the setting to the platform specific storage.
  3569. del settings
  3570. log.debug("App.final_save() --> App UI state saved.")
  3571. QtWidgets.qApp.quit()
  3572. def on_portable_checked(self, state):
  3573. """
  3574. Callback called when the checkbox in Preferences GUI is checked.
  3575. It will set the application as portable by creating the preferences and recent files in the
  3576. 'config' folder found in the FlatCAM installation folder.
  3577. :param state: boolean, the state of the checkbox when clicked/checked
  3578. :return:
  3579. """
  3580. line_no = 0
  3581. data = None
  3582. if sys.platform != 'win32':
  3583. # this won't work in Linux or MacOS
  3584. return
  3585. # test if the app was frozen and choose the path for the configuration file
  3586. if getattr(sys, "frozen", False) is True:
  3587. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3588. else:
  3589. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3590. config_file = current_data_path + '\\configuration.txt'
  3591. try:
  3592. with open(config_file, 'r') as f:
  3593. try:
  3594. data = f.readlines()
  3595. except Exception as e:
  3596. log.debug('App.__init__() -->%s' % str(e))
  3597. return
  3598. except FileNotFoundError:
  3599. pass
  3600. for line in data:
  3601. line = line.strip('\n')
  3602. param = str(line).rpartition('=')
  3603. if param[0] == 'portable':
  3604. break
  3605. line_no += 1
  3606. if state:
  3607. data[line_no] = 'portable=True\n'
  3608. # create the new defauults files
  3609. # create current_defaults.FlatConfig file if there is none
  3610. try:
  3611. f = open(current_data_path + '/current_defaults.FlatConfig')
  3612. f.close()
  3613. except IOError:
  3614. App.log.debug('Creating empty current_defaults.FlatConfig')
  3615. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3616. json.dump({}, f)
  3617. f.close()
  3618. # create factory_defaults.FlatConfig file if there is none
  3619. try:
  3620. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3621. f.close()
  3622. except IOError:
  3623. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3624. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3625. json.dump({}, f)
  3626. f.close()
  3627. try:
  3628. f = open(current_data_path + '/recent.json')
  3629. f.close()
  3630. except IOError:
  3631. App.log.debug('Creating empty recent.json')
  3632. f = open(current_data_path + '/recent.json', 'w')
  3633. json.dump([], f)
  3634. f.close()
  3635. try:
  3636. fp = open(current_data_path + '/recent_projects.json')
  3637. fp.close()
  3638. except IOError:
  3639. App.log.debug('Creating empty recent_projects.json')
  3640. fp = open(current_data_path + '/recent_projects.json', 'w')
  3641. json.dump([], fp)
  3642. fp.close()
  3643. # save the current defaults to the new defaults file
  3644. self.save_defaults(silent=True, data_path=current_data_path)
  3645. self.save_factory_defaults(silent=True, data_path=current_data_path)
  3646. else:
  3647. data[line_no] = 'portable=False\n'
  3648. with open(config_file, 'w') as f:
  3649. f.writelines(data)
  3650. def on_toggle_shell(self):
  3651. """
  3652. Toggle shell: if is visible close it, if it is closed then open it
  3653. :return:
  3654. """
  3655. self.report_usage("on_toggle_shell()")
  3656. if self.ui.shell_dock.isVisible():
  3657. self.ui.shell_dock.hide()
  3658. else:
  3659. self.ui.shell_dock.show()
  3660. def on_register_files(self, obj_type=None):
  3661. """
  3662. Called whenever there is a need to register file extensions with FlatCAM.
  3663. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3664. :param obj_type: the type of object to be register for.
  3665. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3666. :return: None
  3667. """
  3668. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3669. new_reg_path = 'Software\\Classes\\'
  3670. # find if the current user is admin
  3671. try:
  3672. is_admin = os.getuid() == 0
  3673. except AttributeError:
  3674. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3675. if is_admin is True:
  3676. root_path = winreg.HKEY_CLASSES_ROOT
  3677. else:
  3678. root_path = winreg.HKEY_CURRENT_USER
  3679. # create the keys
  3680. def set_reg(name, root_path, new_reg_path, value):
  3681. try:
  3682. winreg.CreateKey(root_path, new_reg_path)
  3683. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3684. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3685. return True
  3686. except WindowsError:
  3687. return False
  3688. # delete key in registry
  3689. def delete_reg(root_path, reg_path, key_to_del):
  3690. key_to_del_path = reg_path + key_to_del
  3691. try:
  3692. winreg.DeleteKey(root_path, key_to_del_path)
  3693. return True
  3694. except WindowsError:
  3695. return False
  3696. if obj_type is None or obj_type == 'excellon':
  3697. exc_list = self.ui.fa_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3698. exc_list = [x for x in exc_list if x != '']
  3699. # register all keys in the Preferences window
  3700. for ext in exc_list:
  3701. new_k = new_reg_path + ext
  3702. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3703. # and unregister those that are no longer in the Preferences windows but are in the file
  3704. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3705. if ext not in exc_list:
  3706. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3707. # now write the updated extensions to the self.defaults
  3708. new_ext = ''
  3709. for ext in exc_list:
  3710. new_ext = new_ext + ext + ', '
  3711. self.defaults["fa_excellon"] = new_ext
  3712. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3713. if obj_type is None or obj_type == 'gcode':
  3714. gco_list = self.ui.fa_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3715. gco_list = [x for x in gco_list if x != '']
  3716. # register all keys in the Preferences window
  3717. for ext in gco_list:
  3718. new_k = new_reg_path + ext
  3719. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3720. # and unregister those that are no longer in the Preferences windows but are in the file
  3721. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3722. if ext not in gco_list:
  3723. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3724. # now write the updated extensions to the self.defaults
  3725. new_ext = ''
  3726. for ext in gco_list:
  3727. new_ext = new_ext + ext + ', '
  3728. self.defaults["fa_gcode"] = new_ext
  3729. self.inform.emit('[success] %s' %
  3730. _("Selected GCode file extensions registered with FlatCAM."))
  3731. if obj_type is None or obj_type == 'gerber':
  3732. grb_list = self.ui.fa_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3733. grb_list = [x for x in grb_list if x != '']
  3734. # register all keys in the Preferences window
  3735. for ext in grb_list:
  3736. new_k = new_reg_path + ext
  3737. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3738. # and unregister those that are no longer in the Preferences windows but are in the file
  3739. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3740. if ext not in grb_list:
  3741. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3742. # now write the updated extensions to the self.defaults
  3743. new_ext = ''
  3744. for ext in grb_list:
  3745. new_ext = new_ext + ext + ', '
  3746. self.defaults["fa_gerber"] = new_ext
  3747. self.inform.emit('[success] %s' %
  3748. _("Selected Gerber file extensions registered with FlatCAM."))
  3749. def on_edit_join(self, name=None):
  3750. """
  3751. Callback for Edit->Join. Joins the selected geometry objects into
  3752. a new one.
  3753. :return: None
  3754. """
  3755. self.report_usage("on_edit_join()")
  3756. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3757. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3758. tooldias = []
  3759. geo_type_list = set()
  3760. objs = self.collection.get_selected()
  3761. if len(objs) < 2:
  3762. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3763. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3764. return 'fail'
  3765. for obj in objs:
  3766. geo_type_list.add(obj.multigeo)
  3767. # if len(geo_type_list) == 1 means that all list elements are the same
  3768. if len(geo_type_list) != 1:
  3769. self.inform.emit('[ERROR] %s' %
  3770. _("Failed join. The Geometry objects are of different types.\n"
  3771. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3772. "convert from one to another and retry joining \n"
  3773. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3774. "the result may not be what was expected. \n"
  3775. "Check the generated GCODE."))
  3776. return
  3777. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3778. if True in geo_type_list:
  3779. def initialize(obj, app):
  3780. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  3781. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3782. for v in obj.tools.values():
  3783. v['data']['name'] = obj_name_multi
  3784. self.new_object("geometry", obj_name_multi, initialize)
  3785. else:
  3786. def initialize(obj, app):
  3787. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  3788. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3789. for v in obj.tools.values():
  3790. v['data']['name'] = obj_name_single
  3791. self.new_object("geometry", obj_name_single, initialize)
  3792. self.should_we_save = True
  3793. def on_edit_join_exc(self):
  3794. """
  3795. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3796. a new Excellon.
  3797. :return: None
  3798. """
  3799. self.report_usage("on_edit_join_exc()")
  3800. objs = self.collection.get_selected()
  3801. for obj in objs:
  3802. if not isinstance(obj, FlatCAMExcellon):
  3803. self.inform.emit('[ERROR_NOTCL] %s' %
  3804. _("Failed. Excellon joining works only on Excellon objects."))
  3805. return
  3806. if len(objs) < 2:
  3807. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3808. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3809. return 'fail'
  3810. def initialize(obj, app):
  3811. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  3812. self.new_object("excellon", 'Combo_Excellon', initialize)
  3813. self.should_we_save = True
  3814. def on_edit_join_grb(self):
  3815. """
  3816. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3817. a new Gerber object.
  3818. :return: None
  3819. """
  3820. self.report_usage("on_edit_join_grb()")
  3821. objs = self.collection.get_selected()
  3822. for obj in objs:
  3823. if not isinstance(obj, FlatCAMGerber):
  3824. self.inform.emit('[ERROR_NOTCL] %s' %
  3825. _("Failed. Gerber joining works only on Gerber objects."))
  3826. return
  3827. if len(objs) < 2:
  3828. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3829. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3830. return 'fail'
  3831. def initialize(obj, app):
  3832. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  3833. self.new_object("gerber", 'Combo_Gerber', initialize)
  3834. self.should_we_save = True
  3835. def on_convert_singlegeo_to_multigeo(self):
  3836. """
  3837. Called for converting a Geometry object from single-geo to multi-geo.
  3838. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3839. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3840. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3841. the solid-geometry of that tool.
  3842. :return: None
  3843. """
  3844. self.report_usage("on_convert_singlegeo_to_multigeo()")
  3845. obj = self.collection.get_active()
  3846. if obj is None:
  3847. self.inform.emit('[ERROR_NOTCL] %s' %
  3848. _("Failed. Select a Geometry Object and try again."))
  3849. return
  3850. if not isinstance(obj, FlatCAMGeometry):
  3851. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3852. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  3853. return
  3854. obj.multigeo = True
  3855. for tooluid, dict_value in obj.tools.items():
  3856. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3857. if not isinstance(obj.solid_geometry, list):
  3858. obj.solid_geometry = [obj.solid_geometry]
  3859. obj.solid_geometry[:] = []
  3860. obj.plot()
  3861. self.should_we_save = True
  3862. self.inform.emit('[success] %s' %
  3863. _("A Geometry object was converted to MultiGeo type."))
  3864. def on_convert_multigeo_to_singlegeo(self):
  3865. """
  3866. Called for converting a Geometry object from multi-geo to single-geo.
  3867. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3868. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3869. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3870. the solid-geometry of that tool.
  3871. :return: None
  3872. """
  3873. self.report_usage("on_convert_multigeo_to_singlegeo()")
  3874. obj = self.collection.get_active()
  3875. if obj is None:
  3876. self.inform.emit('[ERROR_NOTCL] %s' %
  3877. _("Failed. Select a Geometry Object and try again."))
  3878. return
  3879. if not isinstance(obj, FlatCAMGeometry):
  3880. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3881. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  3882. return
  3883. obj.multigeo = False
  3884. total_solid_geometry = []
  3885. for tooluid, dict_value in obj.tools.items():
  3886. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3887. # clear the original geometry
  3888. dict_value['solid_geometry'][:] = []
  3889. obj.solid_geometry = deepcopy(total_solid_geometry)
  3890. obj.plot()
  3891. self.should_we_save = True
  3892. self.inform.emit('[success] %s' %
  3893. _("A Geometry object was converted to SingleGeo type."))
  3894. def on_options_dict_change(self, field):
  3895. """
  3896. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  3897. current project. This feature is no longer used.
  3898. :param field:
  3899. :return:
  3900. """
  3901. self.options_write_form_field(field)
  3902. if field == "units":
  3903. self.set_screen_units(self.options['units'])
  3904. def on_defaults_dict_change(self, field):
  3905. """
  3906. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3907. Edit -> Preferences tab window.
  3908. :param field: the key of the self.defaults dictionary that was changed.
  3909. :return: None
  3910. """
  3911. self.defaults_write_form_field(field)
  3912. if field == "units":
  3913. self.set_screen_units(self.defaults['units'])
  3914. def set_screen_units(self, units):
  3915. """
  3916. Set the FlatCAM units on the status bar.
  3917. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3918. :return: None
  3919. """
  3920. self.ui.units_label.setText("[" + units.lower() + "]")
  3921. def on_toggle_units(self, no_pref=False):
  3922. """
  3923. Callback for the Units radio-button change in the Preferences tab.
  3924. Changes the application's default units adn for the project too.
  3925. If changing the project's units, the change propagates to all of
  3926. the objects in the project.
  3927. :return: None
  3928. """
  3929. self.report_usage("on_toggle_units")
  3930. if self.toggle_units_ignore:
  3931. return
  3932. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3933. # If option is the same, then ignore
  3934. if new_units == self.defaults["units"].upper():
  3935. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  3936. return
  3937. # Options to scale
  3938. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3939. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  3940. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3941. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  3942. "excellon_z_pdepth",
  3943. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3944. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3945. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  3946. "geometry_feedrate_probe",
  3947. 'cncjob_tooldia',
  3948. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  3949. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia"
  3950. "tools_2sided_drilldia", "tools_film_boundary",
  3951. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  3952. "tools_panelize_constrainx", "tools_panelize_constrainy",
  3953. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3954. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  3955. "tools_transform_offset_y",
  3956. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3957. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3958. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3959. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3960. 'global_gridx', 'global_gridy', 'global_snap_max']
  3961. def scale_options(sfactor):
  3962. for dim in dimensions:
  3963. if dim == 'excellon_toolchangexy':
  3964. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3965. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3966. coords_xy[0] *= sfactor
  3967. coords_xy[1] *= sfactor
  3968. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3969. elif dim == 'geometry_toolchangexy':
  3970. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3971. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3972. coords_xy[0] *= sfactor
  3973. coords_xy[1] *= sfactor
  3974. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3975. elif dim == 'geometry_cnctooldia':
  3976. tools_diameters = []
  3977. try:
  3978. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3979. tools_diameters = [eval(a) for a in tools_string if a != '']
  3980. except Exception as e:
  3981. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3982. self.options['geometry_cnctooldia'] = ''
  3983. for t in range(len(tools_diameters)):
  3984. tools_diameters[t] *= sfactor
  3985. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  3986. elif dim == 'tools_ncctools':
  3987. ncctools = []
  3988. try:
  3989. tools_string = self.defaults["tools_ncctools"].split(",")
  3990. ncctools = [eval(a) for a in tools_string if a != '']
  3991. except Exception as e:
  3992. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3993. self.options['tools_ncctools'] = ''
  3994. for t in range(len(ncctools)):
  3995. ncctools[t] *= sfactor
  3996. self.options['tools_ncctools'] += "%f," % ncctools[t]
  3997. elif dim == 'tools_solderpaste_tools':
  3998. sptools = []
  3999. try:
  4000. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4001. sptools = [eval(a) for a in tools_string if a != '']
  4002. except Exception as e:
  4003. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4004. self.options['tools_solderpaste_tools'] = ""
  4005. for t in range(len(sptools)):
  4006. sptools[t] *= sfactor
  4007. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  4008. elif dim == 'tools_solderpaste_xy_toolchange':
  4009. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4010. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4011. sp_coords[0] *= sfactor
  4012. sp_coords[1] *= sfactor
  4013. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  4014. elif dim == 'global_gridx' or dim == 'global_gridy':
  4015. if new_units == 'IN':
  4016. val = 0.1
  4017. try:
  4018. val = float(self.defaults[dim]) * sfactor
  4019. except Exception as e:
  4020. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4021. self.options[dim] = float('%.6f' % val)
  4022. else:
  4023. val = 0.1
  4024. try:
  4025. val = float(self.defaults[dim]) * sfactor
  4026. except Exception as e:
  4027. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4028. self.options[dim] = float('%.4f' % val)
  4029. else:
  4030. val = 0.1
  4031. try:
  4032. val = float(self.options[dim]) * sfactor
  4033. except Exception as e:
  4034. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  4035. self.options[dim] = val
  4036. def scale_defaults(sfactor):
  4037. for dim in dimensions:
  4038. if dim == 'excellon_toolchangexy':
  4039. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4040. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4041. coords_xy[0] *= sfactor
  4042. coords_xy[1] *= sfactor
  4043. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4044. elif dim == 'geometry_toolchangexy':
  4045. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4046. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4047. coords_xy[0] *= sfactor
  4048. coords_xy[1] *= sfactor
  4049. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4050. elif dim == 'geometry_cnctooldia':
  4051. tools_diameters = []
  4052. try:
  4053. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4054. tools_diameters = [eval(a) for a in tools_string if a != '']
  4055. except Exception as e:
  4056. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4057. self.defaults['geometry_cnctooldia'] = ''
  4058. for t in range(len(tools_diameters)):
  4059. tools_diameters[t] *= sfactor
  4060. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4061. elif dim == 'tools_ncctools':
  4062. ncctools = []
  4063. try:
  4064. tools_string = self.defaults["tools_ncctools"].split(",")
  4065. ncctools = [eval(a) for a in tools_string if a != '']
  4066. except Exception as e:
  4067. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4068. self.defaults['tools_ncctools'] = ''
  4069. for t in range(len(ncctools)):
  4070. ncctools[t] *= sfactor
  4071. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  4072. elif dim == 'tools_solderpaste_tools':
  4073. sptools = []
  4074. try:
  4075. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4076. sptools = [eval(a) for a in tools_string if a != '']
  4077. except Exception as e:
  4078. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4079. self.defaults['tools_solderpaste_tools'] = ""
  4080. for t in range(len(sptools)):
  4081. sptools[t] *= sfactor
  4082. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4083. elif dim == 'tools_solderpaste_xy_toolchange':
  4084. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4085. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4086. sp_coords[0] *= sfactor
  4087. sp_coords[1] *= sfactor
  4088. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4089. elif dim == 'global_gridx' or dim == 'global_gridy':
  4090. if new_units == 'IN':
  4091. val = 0.1
  4092. try:
  4093. val = float(self.defaults[dim]) * sfactor
  4094. except Exception as e:
  4095. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4096. self.defaults[dim] = float('%.6f' % val)
  4097. else:
  4098. val = 0.1
  4099. try:
  4100. val = float(self.defaults[dim]) * sfactor
  4101. except Exception as e:
  4102. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4103. self.defaults[dim] = float('%.4f' % val)
  4104. else:
  4105. val = 0.1
  4106. try:
  4107. val = float(self.defaults[dim]) * sfactor
  4108. except Exception as e:
  4109. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4110. self.defaults[dim] = val
  4111. # The scaling factor depending on choice of units.
  4112. factor = 1/25.4
  4113. if new_units == 'MM':
  4114. factor = 25.4
  4115. # Changing project units. Warn user.
  4116. msgbox = QtWidgets.QMessageBox()
  4117. msgbox.setWindowTitle(_("Toggle Units"))
  4118. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4119. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4120. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4121. "properties of all objects to be scaled accordingly.\nContinue?"))
  4122. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4123. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4124. msgbox.setDefaultButton(bt_ok)
  4125. msgbox.exec_()
  4126. response = msgbox.clickedButton()
  4127. if response == bt_ok:
  4128. if no_pref is False:
  4129. self.options_read_form()
  4130. scale_options(factor)
  4131. self.options_write_form()
  4132. self.defaults_read_form()
  4133. scale_defaults(factor)
  4134. self.defaults_write_form(fl_units=new_units)
  4135. # save the defaults to file, some may assume that the conversion is enough and it's not
  4136. self.on_save_button()
  4137. self.should_we_save = True
  4138. # change this only if the workspace is active
  4139. if self.defaults['global_workspace'] is True:
  4140. self.plotcanvas.draw_workspace()
  4141. # adjust the grid values on the main toolbar
  4142. dec = 6 if new_units == 'IN'else 4
  4143. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4144. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4145. if not self.ui.grid_gap_link_cb.isChecked():
  4146. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4147. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4148. for obj in self.collection.get_list():
  4149. obj.convert_units(new_units)
  4150. # make that the properties stored in the object are also updated
  4151. self.object_changed.emit(obj)
  4152. obj.build_ui()
  4153. current = self.collection.get_active()
  4154. if current is not None:
  4155. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4156. if not isinstance(current, FlatCAMGeometry):
  4157. current.to_form()
  4158. self.plot_all()
  4159. self.inform.emit('[success] %s: %s' %
  4160. (_("Converted units to"), new_units))
  4161. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4162. self.set_screen_units(new_units)
  4163. else:
  4164. # Undo toggling
  4165. self.toggle_units_ignore = True
  4166. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4167. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4168. else:
  4169. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4170. self.toggle_units_ignore = False
  4171. self.inform.emit('[WARNING_NOTCL]%s' %
  4172. _(" Units conversion cancelled."))
  4173. self.options_read_form()
  4174. self.defaults_read_form()
  4175. def on_toggle_units_click(self):
  4176. try:
  4177. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4178. except (TypeError, AttributeError):
  4179. pass
  4180. if self.defaults["units"] == 'MM':
  4181. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4182. else:
  4183. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4184. self.on_toggle_units(no_pref=True)
  4185. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4186. lambda: self.on_toggle_units(no_pref=False))
  4187. def on_fullscreen(self):
  4188. self.report_usage("on_fullscreen()")
  4189. if self.toggle_fscreen is False:
  4190. if sys.platform == 'win32':
  4191. self.ui.showFullScreen()
  4192. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4193. tb.setVisible(False)
  4194. self.ui.splitter_left.setVisible(False)
  4195. self.toggle_fscreen = True
  4196. else:
  4197. if sys.platform == 'win32':
  4198. self.ui.showNormal()
  4199. self.restore_toolbar_view()
  4200. self.ui.splitter_left.setVisible(True)
  4201. self.toggle_fscreen = False
  4202. def on_toggle_plotarea(self):
  4203. self.report_usage("on_toggle_plotarea()")
  4204. try:
  4205. name = self.ui.plot_tab_area.widget(0).objectName()
  4206. except AttributeError:
  4207. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4208. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4209. self.ui.plot_tab_area.protectTab(0)
  4210. return
  4211. if name != 'plotarea':
  4212. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4213. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4214. self.ui.plot_tab_area.protectTab(0)
  4215. else:
  4216. self.ui.plot_tab_area.closeTab(0)
  4217. def on_toggle_notebook(self):
  4218. if self.ui.splitter.sizes()[0] == 0:
  4219. self.ui.splitter.setSizes([1, 1])
  4220. else:
  4221. self.ui.splitter.setSizes([0, 1])
  4222. def on_toggle_axis(self):
  4223. self.report_usage("on_toggle_axis()")
  4224. if self.toggle_axis is False:
  4225. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4226. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4227. self.plotcanvas.redraw()
  4228. self.toggle_axis = True
  4229. else:
  4230. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4231. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4232. self.plotcanvas.redraw()
  4233. self.toggle_axis = False
  4234. def on_toggle_grid(self):
  4235. self.report_usage("on_toggle_grid()")
  4236. self.ui.grid_snap_btn.trigger()
  4237. def on_options_combo_change(self, sel):
  4238. """
  4239. Called when the combo box to choose between application defaults and
  4240. project option changes value. The corresponding variables are
  4241. copied to the UI.
  4242. :param sel: The option index that was chosen.
  4243. :return: None
  4244. """
  4245. # combo_sel = self.ui.notebook.combo_options.get_active()
  4246. App.log.debug("Options --> %s" % sel)
  4247. # form = [self.defaults_form, self.options_form][sel]
  4248. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  4249. if sel == 0:
  4250. self.gen_form = self.ui.general_defaults_form
  4251. self.ger_form = self.ui.gerber_defaults_form
  4252. self.exc_form = self.ui.excellon_defaults_form
  4253. self.geo_form = self.ui.geometry_defaults_form
  4254. self.cnc_form = self.ui.cncjob_defaults_form
  4255. self.tools_form = self.ui.tools_defaults_form
  4256. self.fa_form = self.ui.fa_defaults_form
  4257. elif sel == 1:
  4258. self.gen_form = self.ui.general_options_form
  4259. self.ger_form = self.ui.gerber_options_form
  4260. self.exc_form = self.ui.excellon_options_form
  4261. self.geo_form = self.ui.geometry_options_form
  4262. self.cnc_form = self.ui.cncjob_options_form
  4263. self.tools_form = self.ui.tools_options_form
  4264. self.fa_form = self.ui.fa_options_form
  4265. else:
  4266. return
  4267. try:
  4268. self.ui.general_scroll_area.takeWidget()
  4269. except:
  4270. self.log.debug("Nothing to remove")
  4271. self.ui.general_scroll_area.setWidget(self.gen_form)
  4272. self.gen_form.show()
  4273. try:
  4274. self.ui.gerber_scroll_area.takeWidget()
  4275. except:
  4276. self.log.debug("Nothing to remove")
  4277. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4278. self.ger_form.show()
  4279. try:
  4280. self.ui.excellon_scroll_area.takeWidget()
  4281. except:
  4282. self.log.debug("Nothing to remove")
  4283. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4284. self.exc_form.show()
  4285. try:
  4286. self.ui.geometry_scroll_area.takeWidget()
  4287. except:
  4288. self.log.debug("Nothing to remove")
  4289. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4290. self.geo_form.show()
  4291. try:
  4292. self.ui.cncjob_scroll_area.takeWidget()
  4293. except:
  4294. self.log.debug("Nothing to remove")
  4295. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4296. self.cnc_form.show()
  4297. try:
  4298. self.ui.tools_scroll_area.takeWidget()
  4299. except:
  4300. self.log.debug("Nothing to remove")
  4301. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4302. self.tools_form.show()
  4303. try:
  4304. self.ui.fa_scroll_area.takeWidget()
  4305. except:
  4306. self.log.debug("Nothing to remove")
  4307. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4308. self.fa_form.show()
  4309. self.log.debug("Finished GUI form initialization.")
  4310. # self.options2form()
  4311. def on_excellon_defaults_button(self):
  4312. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  4313. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  4314. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  4315. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  4316. self.defaults_form_fields["excellon_zeros"].set_value('L')
  4317. self.defaults_form_fields["excellon_units"].set_value('INCH')
  4318. log.debug("Excellon app defaults loaded ...")
  4319. def on_excellon_options_button(self):
  4320. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  4321. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  4322. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  4323. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  4324. self.options_form_fields["excellon_zeros"].set_value('L')
  4325. self.options_form_fields["excellon_units"].set_value('INCH')
  4326. log.debug("Excellon options defaults loaded ...")
  4327. def on_update_exc_export(self, state):
  4328. """
  4329. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  4330. if the update_excellon_cb checkbox is checked
  4331. :param state: state of the checkbox whose signals is tied to his slot
  4332. :return:
  4333. """
  4334. if state:
  4335. # first try to disconnect
  4336. try:
  4337. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.\
  4338. disconnect(self.on_excellon_format_changed)
  4339. except TypeError:
  4340. pass
  4341. try:
  4342. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.\
  4343. disconnect(self.on_excellon_format_changed)
  4344. except TypeError:
  4345. pass
  4346. try:
  4347. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.\
  4348. disconnect(self.on_excellon_format_changed)
  4349. except TypeError:
  4350. pass
  4351. try:
  4352. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.\
  4353. disconnect(self.on_excellon_format_changed)
  4354. except TypeError:
  4355. pass
  4356. try:
  4357. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  4358. disconnect(self.on_excellon_zeros_changed)
  4359. except TypeError:
  4360. pass
  4361. try:
  4362. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  4363. disconnect(self.on_excellon_zeros_changed)
  4364. except TypeError:
  4365. pass
  4366. # the connect them
  4367. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.connect(
  4368. self.on_excellon_format_changed)
  4369. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.connect(
  4370. self.on_excellon_format_changed)
  4371. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.connect(
  4372. self.on_excellon_format_changed)
  4373. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.connect(
  4374. self.on_excellon_format_changed)
  4375. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  4376. self.on_excellon_zeros_changed)
  4377. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  4378. self.on_excellon_units_changed)
  4379. else:
  4380. # disconnect the signals
  4381. try:
  4382. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged. \
  4383. disconnect(self.on_excellon_format_changed)
  4384. except TypeError:
  4385. pass
  4386. try:
  4387. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged. \
  4388. disconnect(self.on_excellon_format_changed)
  4389. except TypeError:
  4390. pass
  4391. try:
  4392. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged. \
  4393. disconnect(self.on_excellon_format_changed)
  4394. except TypeError:
  4395. pass
  4396. try:
  4397. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged. \
  4398. disconnect(self.on_excellon_format_changed)
  4399. except TypeError:
  4400. pass
  4401. try:
  4402. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  4403. disconnect(self.on_excellon_zeros_changed)
  4404. except TypeError:
  4405. pass
  4406. try:
  4407. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  4408. disconnect(self.on_excellon_zeros_changed)
  4409. except TypeError:
  4410. pass
  4411. def on_excellon_format_changed(self):
  4412. """
  4413. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  4414. :return: None
  4415. """
  4416. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  4417. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4418. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  4419. )
  4420. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4421. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  4422. )
  4423. else:
  4424. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4425. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  4426. )
  4427. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4428. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  4429. )
  4430. def on_excellon_zeros_changed(self):
  4431. """
  4432. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  4433. :return: None
  4434. """
  4435. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  4436. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  4437. )
  4438. def on_excellon_units_changed(self):
  4439. """
  4440. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  4441. :return: None
  4442. """
  4443. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  4444. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  4445. )
  4446. self.on_excellon_format_changed()
  4447. # Setting plot colors handlers
  4448. def on_pf_color_entry(self):
  4449. self.defaults['global_plot_fill'] = \
  4450. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  4451. self.defaults['global_plot_fill'][7:9]
  4452. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4453. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  4454. def on_pf_color_button(self):
  4455. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  4456. c_dialog = QtWidgets.QColorDialog()
  4457. plot_fill_color = c_dialog.getColor(initial=current_color)
  4458. if plot_fill_color.isValid() is False:
  4459. return
  4460. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4461. "background-color:%s" % str(plot_fill_color.name()))
  4462. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  4463. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  4464. self.defaults['global_plot_fill'] = new_val
  4465. def on_pf_color_spinner(self):
  4466. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  4467. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  4468. self.defaults['global_plot_fill'] = \
  4469. self.defaults['global_plot_fill'][:7] + \
  4470. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4471. self.defaults['global_plot_line'] = \
  4472. self.defaults['global_plot_line'][:7] + \
  4473. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4474. def on_pf_color_slider(self):
  4475. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  4476. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  4477. def on_pl_color_entry(self):
  4478. self.defaults['global_plot_line'] = \
  4479. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  4480. self.defaults['global_plot_line'][7:9]
  4481. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4482. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  4483. def on_pl_color_button(self):
  4484. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  4485. # print(current_color)
  4486. c_dialog = QtWidgets.QColorDialog()
  4487. plot_line_color = c_dialog.getColor(initial=current_color)
  4488. if plot_line_color.isValid() is False:
  4489. return
  4490. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4491. "background-color:%s" % str(plot_line_color.name()))
  4492. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  4493. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  4494. self.defaults['global_plot_line'] = new_val_line
  4495. # Setting selection colors (left - right) handlers
  4496. def on_sf_color_entry(self):
  4497. self.defaults['global_sel_fill'] = \
  4498. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  4499. self.defaults['global_sel_fill'][7:9]
  4500. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4501. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  4502. def on_sf_color_button(self):
  4503. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  4504. c_dialog = QtWidgets.QColorDialog()
  4505. plot_fill_color = c_dialog.getColor(initial=current_color)
  4506. if plot_fill_color.isValid() is False:
  4507. return
  4508. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4509. "background-color:%s" % str(plot_fill_color.name()))
  4510. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  4511. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  4512. self.defaults['global_sel_fill'] = new_val
  4513. def on_sf_color_spinner(self):
  4514. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  4515. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  4516. self.defaults['global_sel_fill'] = \
  4517. self.defaults['global_sel_fill'][:7] + \
  4518. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4519. self.defaults['global_sel_line'] = \
  4520. self.defaults['global_sel_line'][:7] + \
  4521. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4522. def on_sf_color_slider(self):
  4523. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  4524. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  4525. def on_sl_color_entry(self):
  4526. self.defaults['global_sel_line'] = \
  4527. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  4528. self.defaults['global_sel_line'][7:9]
  4529. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4530. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  4531. def on_sl_color_button(self):
  4532. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  4533. c_dialog = QtWidgets.QColorDialog()
  4534. plot_line_color = c_dialog.getColor(initial=current_color)
  4535. if plot_line_color.isValid() is False:
  4536. return
  4537. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4538. "background-color:%s" % str(plot_line_color.name()))
  4539. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  4540. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  4541. self.defaults['global_sel_line'] = new_val_line
  4542. # Setting selection colors (right - left) handlers
  4543. def on_alt_sf_color_entry(self):
  4544. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  4545. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  4546. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4547. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  4548. def on_alt_sf_color_button(self):
  4549. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  4550. c_dialog = QtWidgets.QColorDialog()
  4551. plot_fill_color = c_dialog.getColor(initial=current_color)
  4552. if plot_fill_color.isValid() is False:
  4553. return
  4554. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4555. "background-color:%s" % str(plot_fill_color.name()))
  4556. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  4557. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  4558. self.defaults['global_alt_sel_fill'] = new_val
  4559. def on_alt_sf_color_spinner(self):
  4560. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  4561. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  4562. self.defaults['global_alt_sel_fill'] = \
  4563. self.defaults['global_alt_sel_fill'][:7] + \
  4564. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4565. self.defaults['global_alt_sel_line'] = \
  4566. self.defaults['global_alt_sel_line'][:7] + \
  4567. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4568. def on_alt_sf_color_slider(self):
  4569. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  4570. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  4571. def on_alt_sl_color_entry(self):
  4572. self.defaults['global_alt_sel_line'] = \
  4573. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  4574. self.defaults['global_alt_sel_line'][7:9]
  4575. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4576. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  4577. def on_alt_sl_color_button(self):
  4578. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  4579. c_dialog = QtWidgets.QColorDialog()
  4580. plot_line_color = c_dialog.getColor(initial=current_color)
  4581. if plot_line_color.isValid() is False:
  4582. return
  4583. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4584. "background-color:%s" % str(plot_line_color.name()))
  4585. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  4586. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  4587. self.defaults['global_alt_sel_line'] = new_val_line
  4588. # Setting Editor colors
  4589. def on_draw_color_entry(self):
  4590. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  4591. .draw_color_entry.get_value()
  4592. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  4593. "background-color:%s" % str(self.defaults['global_draw_color']))
  4594. def on_draw_color_button(self):
  4595. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  4596. c_dialog = QtWidgets.QColorDialog()
  4597. draw_color = c_dialog.getColor(initial=current_color)
  4598. if draw_color.isValid() is False:
  4599. return
  4600. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  4601. "background-color:%s" % str(draw_color.name()))
  4602. new_val = str(draw_color.name())
  4603. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  4604. self.defaults['global_draw_color'] = new_val
  4605. def on_sel_draw_color_entry(self):
  4606. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  4607. .sel_draw_color_entry.get_value()
  4608. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  4609. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  4610. def on_sel_draw_color_button(self):
  4611. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  4612. c_dialog = QtWidgets.QColorDialog()
  4613. sel_draw_color = c_dialog.getColor(initial=current_color)
  4614. if sel_draw_color.isValid() is False:
  4615. return
  4616. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  4617. "background-color:%s" % str(sel_draw_color.name()))
  4618. new_val_sel = str(sel_draw_color.name())
  4619. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  4620. self.defaults['global_sel_draw_color'] = new_val_sel
  4621. def on_proj_color_entry(self):
  4622. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  4623. .proj_color_entry.get_value()
  4624. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  4625. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  4626. def on_proj_color_button(self):
  4627. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  4628. c_dialog = QtWidgets.QColorDialog()
  4629. proj_color = c_dialog.getColor(initial=current_color)
  4630. if proj_color.isValid() is False:
  4631. return
  4632. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  4633. "background-color:%s" % str(proj_color.name()))
  4634. new_val_sel = str(proj_color.name())
  4635. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  4636. self.defaults['global_proj_item_color'] = new_val_sel
  4637. def on_proj_color_dis_entry(self):
  4638. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  4639. .proj_color_dis_entry.get_value()
  4640. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  4641. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  4642. def on_proj_color_dis_button(self):
  4643. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  4644. c_dialog = QtWidgets.QColorDialog()
  4645. proj_color = c_dialog.getColor(initial=current_color)
  4646. if proj_color.isValid() is False:
  4647. return
  4648. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  4649. "background-color:%s" % str(proj_color.name()))
  4650. new_val_sel = str(proj_color.name())
  4651. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  4652. self.defaults['global_proj_item_dis_color'] = new_val_sel
  4653. def on_annotation_fontcolor_entry(self):
  4654. self.defaults['cncjob_annotation_fontcolor'] = \
  4655. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.get_value()
  4656. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  4657. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  4658. def on_annotation_fontcolor_button(self):
  4659. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  4660. c_dialog = QtWidgets.QColorDialog()
  4661. annotation_color = c_dialog.getColor(initial=current_color)
  4662. if annotation_color.isValid() is False:
  4663. return
  4664. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  4665. "background-color:%s" % str(annotation_color.name()))
  4666. new_val_sel = str(annotation_color.name())
  4667. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.set_value(new_val_sel)
  4668. self.defaults['global_proj_item_dis_color'] = new_val_sel
  4669. def on_splash_changed(self, state):
  4670. settings = QSettings("Open Source", "FlatCAM")
  4671. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  4672. # This will write the setting to the platform specific storage.
  4673. del settings
  4674. def on_notebook_tab_rmb_click(self, checked):
  4675. self.ui.notebook.set_detachable(val=checked)
  4676. self.defaults["global_tabs_detachable"] = checked
  4677. self.ui.plot_tab_area.set_detachable(val=checked)
  4678. self.defaults["global_tabs_detachable"] = checked
  4679. def on_deselect_all(self):
  4680. self.collection.set_all_inactive()
  4681. self.delete_selection_shape()
  4682. def on_workspace_modified(self):
  4683. self.save_defaults(silent=True)
  4684. self.plotcanvas.draw_workspace()
  4685. def on_workspace(self):
  4686. self.report_usage("on_workspace()")
  4687. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  4688. self.plotcanvas.restore_workspace()
  4689. else:
  4690. self.plotcanvas.delete_workspace()
  4691. self.save_defaults(silent=True)
  4692. def on_workspace_menu(self):
  4693. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  4694. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  4695. else:
  4696. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  4697. self.on_workspace()
  4698. def on_layout(self, index=None, lay=None):
  4699. self.report_usage("on_layout()")
  4700. if lay:
  4701. current_layout = lay
  4702. else:
  4703. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  4704. settings = QSettings("Open Source", "FlatCAM")
  4705. settings.setValue('layout', current_layout)
  4706. # This will write the setting to the platform specific storage.
  4707. del settings
  4708. # first remove the toolbars:
  4709. try:
  4710. self.ui.removeToolBar(self.ui.toolbarfile)
  4711. self.ui.removeToolBar(self.ui.toolbargeo)
  4712. self.ui.removeToolBar(self.ui.toolbarview)
  4713. self.ui.removeToolBar(self.ui.toolbarshell)
  4714. self.ui.removeToolBar(self.ui.toolbartools)
  4715. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  4716. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  4717. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  4718. self.ui.removeToolBar(self.ui.snap_toolbar)
  4719. self.ui.removeToolBar(self.ui.toolbarshell)
  4720. except Exception as e:
  4721. pass
  4722. if current_layout == 'standard':
  4723. # ## TOOLBAR INSTALLATION # ##
  4724. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  4725. self.ui.toolbarfile.setObjectName('File_TB')
  4726. self.ui.addToolBar(self.ui.toolbarfile)
  4727. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  4728. self.ui.toolbargeo.setObjectName('Edit_TB')
  4729. self.ui.addToolBar(self.ui.toolbargeo)
  4730. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  4731. self.ui.toolbarview.setObjectName('View_TB')
  4732. self.ui.addToolBar(self.ui.toolbarview)
  4733. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  4734. self.ui.toolbarshell.setObjectName('Shell_TB')
  4735. self.ui.addToolBar(self.ui.toolbarshell)
  4736. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  4737. self.ui.toolbartools.setObjectName('Tools_TB')
  4738. self.ui.addToolBar(self.ui.toolbartools)
  4739. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  4740. # self.ui.exc_edit_toolbar.setVisible(False)
  4741. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  4742. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  4743. self.ui.addToolBarBreak()
  4744. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  4745. # self.ui.geo_edit_toolbar.setVisible(False)
  4746. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  4747. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  4748. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  4749. # self.ui.grb_edit_toolbar.setVisible(False)
  4750. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  4751. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  4752. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  4753. self.ui.snap_toolbar.setObjectName('Snap_TB')
  4754. # self.ui.snap_toolbar.setMaximumHeight(30)
  4755. self.ui.addToolBar(self.ui.snap_toolbar)
  4756. self.ui.corner_snap_btn.setVisible(False)
  4757. self.ui.snap_magnet.setVisible(False)
  4758. elif current_layout == 'compact':
  4759. # ## TOOLBAR INSTALLATION # ##
  4760. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  4761. self.ui.toolbarfile.setObjectName('File_TB')
  4762. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  4763. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  4764. self.ui.toolbargeo.setObjectName('Edit_TB')
  4765. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  4766. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  4767. self.ui.toolbarshell.setObjectName('Shell_TB')
  4768. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  4769. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  4770. self.ui.toolbartools.setObjectName('Tools_TB')
  4771. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  4772. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  4773. # self.ui.geo_edit_toolbar.setVisible(False)
  4774. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  4775. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  4776. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  4777. self.ui.toolbarview.setObjectName('View_TB')
  4778. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  4779. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  4780. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  4781. # self.ui.grb_edit_toolbar.setVisible(False)
  4782. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  4783. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  4784. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  4785. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  4786. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  4787. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  4788. self.ui.snap_toolbar.setObjectName('Snap_TB')
  4789. self.ui.snap_toolbar.setMaximumHeight(30)
  4790. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  4791. self.ui.corner_snap_btn.setVisible(True)
  4792. self.ui.snap_magnet.setVisible(True)
  4793. # add all the actions to the toolbars
  4794. self.ui.populate_toolbars()
  4795. # reconnect all the signals to the toolbar actions
  4796. self.connect_toolbar_signals()
  4797. self.ui.grid_snap_btn.setChecked(True)
  4798. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  4799. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  4800. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  4801. self.ui.grid_gap_link_cb.setChecked(True)
  4802. def on_cnc_custom_parameters(self, signal_text):
  4803. if signal_text == 'Parameters':
  4804. return
  4805. else:
  4806. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  4807. def on_save_button(self):
  4808. log.debug("App.on_save_button() --> Saving preferences to file.")
  4809. self.preferences_changed_flag = False
  4810. self.save_defaults(silent=False)
  4811. # load the defaults so they are updated into the app
  4812. self.load_defaults(filename='current_defaults')
  4813. # Re-fresh project options
  4814. self.on_options_app2project()
  4815. # save the notebook font size
  4816. settings = QSettings("Open Source", "FlatCAM")
  4817. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4818. settings.setValue('notebook_font_size', fsize)
  4819. # save the axis font size
  4820. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  4821. settings.setValue('axis_font_size', g_fsize)
  4822. # This will write the setting to the platform specific storage.
  4823. del settings
  4824. def handlePrint(self):
  4825. self.report_usage("handlePrint()")
  4826. dialog = QtPrintSupport.QPrintDialog()
  4827. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  4828. self.ui.code_editor.document().print_(dialog.printer())
  4829. def handlePreview(self):
  4830. self.report_usage("handlePreview()")
  4831. dialog = QtPrintSupport.QPrintPreviewDialog()
  4832. dialog.paintRequested.connect(self.ui.code_editor.print_)
  4833. dialog.exec_()
  4834. def handleTextChanged(self):
  4835. # enable = not self.ui.code_editor.document().isEmpty()
  4836. # self.ui.buttonPrint.setEnabled(enable)
  4837. # self.ui.buttonPreview.setEnabled(enable)
  4838. pass
  4839. def handleOpen(self, filt=None):
  4840. self.report_usage("handleOpen()")
  4841. if filt:
  4842. _filter_ = filt
  4843. else:
  4844. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  4845. "All Files (*.*)"
  4846. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  4847. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  4848. if path:
  4849. file = QtCore.QFile(path)
  4850. if file.open(QtCore.QIODevice.ReadOnly):
  4851. stream = QtCore.QTextStream(file)
  4852. self.gcode_edited = stream.readAll()
  4853. self.ui.code_editor.setPlainText(self.gcode_edited)
  4854. file.close()
  4855. def handleSaveGCode(self, name=None, filt=None):
  4856. self.report_usage("handleSaveGCode()")
  4857. if filt:
  4858. _filter_ = filt
  4859. else:
  4860. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  4861. "All Files (*.*)"
  4862. if name:
  4863. obj_name = name
  4864. else:
  4865. try:
  4866. obj_name = self.collection.get_active().options['name']
  4867. except AttributeError:
  4868. obj_name = 'file'
  4869. if filt is None:
  4870. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  4871. try:
  4872. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  4873. caption=_("Export G-Code ..."),
  4874. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  4875. filter=_filter_
  4876. )[0])
  4877. except TypeError:
  4878. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  4879. if filename == "":
  4880. self.inform.emit('[WARNING_NOTCL] %s' %
  4881. _("Export Code cancelled."))
  4882. return
  4883. else:
  4884. try:
  4885. my_gcode = self.ui.code_editor.toPlainText()
  4886. with open(filename, 'w') as f:
  4887. for line in my_gcode:
  4888. f.write(line)
  4889. except FileNotFoundError:
  4890. self.inform.emit('[WARNING] %s' %
  4891. _("No such file or directory"))
  4892. return
  4893. except PermissionError:
  4894. self.inform.emit('[WARNING] %s' %
  4895. _("Permission denied, saving not possible.\n"
  4896. "Most likely another app is holding the file open and not accessible."))
  4897. return
  4898. # Just for adding it to the recent files list.
  4899. if self.defaults["global_open_style"] is False:
  4900. self.file_opened.emit("cncjob", filename)
  4901. self.file_saved.emit("cncjob", filename)
  4902. self.inform.emit('%s: %s' % (_("Saved to"), str(filename)))
  4903. def handleFindGCode(self):
  4904. self.report_usage("handleFindGCode()")
  4905. flags = QtGui.QTextDocument.FindCaseSensitively
  4906. text_to_be_found = self.ui.entryFind.get_value()
  4907. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  4908. if r is False:
  4909. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4910. def handleReplaceGCode(self):
  4911. self.report_usage("handleReplaceGCode()")
  4912. old = self.ui.entryFind.get_value()
  4913. new = self.ui.entryReplace.get_value()
  4914. if self.ui.sel_all_cb.isChecked():
  4915. while True:
  4916. cursor = self.ui.code_editor.textCursor()
  4917. cursor.beginEditBlock()
  4918. flags = QtGui.QTextDocument.FindCaseSensitively
  4919. # self.ui.editor is the QPlainTextEdit
  4920. r = self.ui.code_editor.find(str(old), flags)
  4921. if r:
  4922. qc = self.ui.code_editor.textCursor()
  4923. if qc.hasSelection():
  4924. qc.insertText(new)
  4925. else:
  4926. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4927. break
  4928. # Mark end of undo block
  4929. cursor.endEditBlock()
  4930. else:
  4931. cursor = self.ui.code_editor.textCursor()
  4932. cursor.beginEditBlock()
  4933. qc = self.ui.code_editor.textCursor()
  4934. if qc.hasSelection():
  4935. qc.insertText(new)
  4936. # Mark end of undo block
  4937. cursor.endEditBlock()
  4938. def handleRunCode(self):
  4939. # trying to run a Tcl command without having the Shell open will create some warnings because the Tcl Shell
  4940. # tries to print on a hidden widget, therefore show the dock if hidden
  4941. if self.ui.shell_dock.isHidden():
  4942. self.ui.shell_dock.show()
  4943. script_code = self.ui.code_editor.toPlainText()
  4944. # self.shell._sysShell.exec_command(script_code)
  4945. old_line = ''
  4946. for tcl_command_line in script_code.splitlines():
  4947. # do not process lines starting with '#' = comment and empty lines
  4948. if not tcl_command_line.startswith('#') and tcl_command_line != '':
  4949. # id FlatCAM is run in Windows then replace all the slashes with
  4950. # the UNIX style slash that TCL understands
  4951. if sys.platform == 'win32':
  4952. if "open" in tcl_command_line:
  4953. tcl_command_line = tcl_command_line.replace('\\', '/')
  4954. if old_line != '':
  4955. new_command = old_line + tcl_command_line + '\n'
  4956. else:
  4957. new_command = tcl_command_line
  4958. # execute the actual Tcl command
  4959. try:
  4960. self.shell.open_proccessing() # Disables input box.
  4961. result = self.tcl.eval(str(new_command))
  4962. if result != 'None':
  4963. self.shell.append_output(result + '\n')
  4964. old_line = ''
  4965. except tk.TclError as e:
  4966. old_line = old_line + tcl_command_line + '\n'
  4967. if old_line != '':
  4968. # it means that the script finished with an error
  4969. result = self.tcl.eval("set errorInfo")
  4970. self.log.error("Exec command Exception: %s" % (result + '\n'))
  4971. self.shell.append_error('ERROR: ' + result + '\n')
  4972. else:
  4973. # success! plot all objects
  4974. self.plot_all()
  4975. self.shell.close_proccessing()
  4976. def on_tool_add_keypress(self):
  4977. # ## Current application units in Upper Case
  4978. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4979. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4980. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4981. if notebook_widget_name == 'selected_tab':
  4982. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  4983. # Tool add works for Geometry only if Advanced is True in Preferences
  4984. if self.defaults["global_app_level"] == 'a':
  4985. tool_add_popup = FCInputDialog(title="New Tool ...",
  4986. text='Enter a Tool Diameter:',
  4987. min=0.0000, max=99.9999, decimals=4)
  4988. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  4989. val, ok = tool_add_popup.get_value()
  4990. if ok:
  4991. if float(val) == 0:
  4992. self.inform.emit('[WARNING_NOTCL] %s' %
  4993. _("Please enter a tool diameter with non-zero value, in Float format."))
  4994. return
  4995. self.collection.get_active().on_tool_add(dia=float(val))
  4996. else:
  4997. self.inform.emit('[WARNING_NOTCL] %s...' %
  4998. _("Adding Tool cancelled"))
  4999. else:
  5000. msgbox = QtWidgets.QMessageBox()
  5001. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5002. "Go to Preferences -> General - Show Advanced Options."))
  5003. msgbox.setWindowTitle("Tool adding ...")
  5004. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5005. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5006. msgbox.setDefaultButton(bt_ok)
  5007. msgbox.exec_()
  5008. # work only if the notebook tab on focus is the Tools_Tab
  5009. if notebook_widget_name == 'tool_tab':
  5010. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5011. tool_add_popup = FCInputDialog(title="New Tool ...",
  5012. text='Enter a Tool Diameter:',
  5013. min=0.0000, max=99.9999, decimals=4)
  5014. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5015. val, ok = tool_add_popup.get_value()
  5016. # and only if the tool is NCC Tool
  5017. if tool_widget == self.ncclear_tool.toolName:
  5018. if ok:
  5019. if float(val) == 0:
  5020. self.inform.emit('[WARNING_NOTCL] %s' %
  5021. _("Please enter a tool diameter with non-zero value, in Float format."))
  5022. return
  5023. self.ncclear_tool.on_tool_add(dia=float(val))
  5024. else:
  5025. self.inform.emit('[WARNING_NOTCL] %s...' %
  5026. _("Adding Tool cancelled"))
  5027. # and only if the tool is Paint Area Tool
  5028. elif tool_widget == self.paint_tool.toolName:
  5029. if ok:
  5030. if float(val) == 0:
  5031. self.inform.emit('[WARNING_NOTCL] %s' %
  5032. _("Please enter a tool diameter with non-zero value, in Float format."))
  5033. return
  5034. self.paint_tool.on_tool_add(dia=float(val))
  5035. else:
  5036. self.inform.emit('[WARNING_NOTCL] %s...' %
  5037. _("Adding Tool cancelled"))
  5038. # and only if the tool is Solder Paste Dispensing Tool
  5039. elif tool_widget == self.paste_tool.toolName:
  5040. if ok:
  5041. if float(val) == 0:
  5042. self.inform.emit('[WARNING_NOTCL] %s' %
  5043. _("Please enter a tool diameter with non-zero value, in Float format."))
  5044. return
  5045. self.paste_tool.on_tool_add(dia=float(val))
  5046. else:
  5047. self.inform.emit('[WARNING_NOTCL] %s...' %
  5048. _("Adding Tool cancelled"))
  5049. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5050. # See description bellow.
  5051. def on_delete_keypress(self):
  5052. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5053. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5054. if notebook_widget_name == 'selected_tab':
  5055. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5056. self.collection.get_active().on_tool_delete()
  5057. # work only if the notebook tab on focus is the Tools_Tab
  5058. elif notebook_widget_name == 'tool_tab':
  5059. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5060. # and only if the tool is NCC Tool
  5061. if tool_widget == self.ncclear_tool.toolName:
  5062. self.ncclear_tool.on_tool_delete()
  5063. # and only if the tool is Paint Tool
  5064. elif tool_widget == self.paint_tool.toolName:
  5065. self.paint_tool.on_tool_delete()
  5066. # and only if the tool is Solder Paste Dispensing Tool
  5067. elif tool_widget == self.paste_tool.toolName:
  5068. self.paste_tool.on_tool_delete()
  5069. else:
  5070. self.on_delete()
  5071. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5072. # some screens you have to be careful where you hover with your mouse.
  5073. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5074. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5075. # Complicated, I know :)
  5076. def on_delete(self):
  5077. """
  5078. Delete the currently selected FlatCAMObjs.
  5079. :return: None
  5080. """
  5081. self.report_usage("on_delete()")
  5082. response = None
  5083. bt_ok = None
  5084. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5085. # a geometry object before we update it.
  5086. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5087. and self.grb_editor.editor_active is False:
  5088. if self.defaults["global_delete_confirmation"] is True:
  5089. msgbox = QtWidgets.QMessageBox()
  5090. msgbox.setWindowTitle(_("Delete objects"))
  5091. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5092. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5093. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5094. "the selected objects?"))
  5095. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5096. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5097. msgbox.setDefaultButton(bt_ok)
  5098. msgbox.exec_()
  5099. response = msgbox.clickedButton()
  5100. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5101. if self.collection.get_active():
  5102. self.log.debug("App.on_delete()")
  5103. while self.collection.get_active():
  5104. obj_active = self.collection.get_active()
  5105. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5106. if isinstance(obj_active, FlatCAMGerber):
  5107. for el in obj_active.mark_shapes:
  5108. obj_active.mark_shapes[el].clear(update=True)
  5109. obj_active.mark_shapes[el].enabled = False
  5110. # obj_active.mark_shapes[el] = None
  5111. del el
  5112. elif isinstance(obj_active, FlatCAMCNCjob):
  5113. try:
  5114. obj_active.annotation.clear(update=True)
  5115. obj_active.annotation.enabled = False
  5116. except AttributeError:
  5117. pass
  5118. self.delete_first_selected()
  5119. self.inform.emit('%s...' %
  5120. _("Object(s) deleted"))
  5121. # make sure that the selection shape is deleted, too
  5122. self.delete_selection_shape()
  5123. else:
  5124. self.inform.emit(_("Failed. No object(s) selected..."))
  5125. else:
  5126. self.inform.emit(_("Save the work in Editor and try again ..."))
  5127. def delete_first_selected(self):
  5128. # Keep this for later
  5129. try:
  5130. sel_obj = self.collection.get_active()
  5131. name = sel_obj.options["name"]
  5132. except AttributeError:
  5133. self.log.debug("Nothing selected for deletion")
  5134. return
  5135. # Remove from dictionary
  5136. self.collection.delete_active()
  5137. # Clear form
  5138. self.setup_component_editor()
  5139. self.inform.emit('%s: %s' %
  5140. (_("Object deleted"), name))
  5141. def on_set_origin(self):
  5142. """
  5143. Set the origin to the left mouse click position
  5144. :return: None
  5145. """
  5146. # display the message for the user
  5147. # and ask him to click on the desired position
  5148. self.report_usage("on_set_origin()")
  5149. def origin_replot():
  5150. def worker_task():
  5151. with self.proc_container.new('%s...' % _("Plotting")):
  5152. for obj in self.collection.get_list():
  5153. obj.plot()
  5154. self.plotcanvas.fit_view()
  5155. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  5156. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5157. self.inform.emit(_('Click to set the origin ...'))
  5158. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  5159. # first disconnect it as it may have been used by something else
  5160. try:
  5161. self.replot_signal.disconnect()
  5162. except TypeError:
  5163. pass
  5164. self.replot_signal[list].connect(origin_replot)
  5165. def on_set_zero_click(self, event):
  5166. # this function will be available only for mouse left click
  5167. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5168. if event.button == 1:
  5169. if self.grid_status() == True:
  5170. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5171. else:
  5172. pos = pos_canvas
  5173. x = 0 - pos[0]
  5174. y = 0 - pos[1]
  5175. def worker_task():
  5176. with self.proc_container.new(_("Setting Origin...")):
  5177. for obj in self.collection.get_list():
  5178. obj.offset((x, y))
  5179. self.object_changed.emit(obj)
  5180. # Update the object bounding box options
  5181. a, b, c, d = obj.bounds()
  5182. obj.options['xmin'] = a
  5183. obj.options['ymin'] = b
  5184. obj.options['xmax'] = c
  5185. obj.options['ymax'] = d
  5186. self.inform.emit('[success]%s...' %
  5187. _('Origin set'))
  5188. self.replot_signal.emit([])
  5189. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5190. self.should_we_save = True
  5191. def on_jump_to(self, custom_location=None, fit_center=True):
  5192. """
  5193. Jump to a location by setting the mouse cursor location
  5194. :return:
  5195. """
  5196. self.report_usage("on_jump_to()")
  5197. if not custom_location:
  5198. dia_box = Dialog_box(title=_("Jump to ..."),
  5199. label=_("Enter the coordinates in format X,Y:"),
  5200. icon=QtGui.QIcon('share/jump_to16.png'))
  5201. if dia_box.ok is True:
  5202. try:
  5203. location = eval(dia_box.location)
  5204. if not isinstance(location, tuple):
  5205. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  5206. return
  5207. except:
  5208. return
  5209. else:
  5210. return
  5211. else:
  5212. location = custom_location
  5213. if fit_center:
  5214. self.plotcanvas.fit_center(loc=location)
  5215. cursor = QtGui.QCursor()
  5216. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5217. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  5218. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  5219. self.inform.emit('[success] %s' %
  5220. _("Done."))
  5221. return location
  5222. def on_copy_object(self):
  5223. self.report_usage("on_copy_object()")
  5224. def initialize(obj_init, app):
  5225. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5226. try:
  5227. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5228. except AttributeError:
  5229. pass
  5230. try:
  5231. obj_init.apertures = deepcopy(obj.apertures)
  5232. except AttributeError:
  5233. pass
  5234. try:
  5235. if obj.tools:
  5236. obj_init.tools = deepcopy(obj.tools)
  5237. except Exception as e:
  5238. log.debug("App.on_copy_object() --> %s" % str(e))
  5239. def initialize_excellon(obj_init, app):
  5240. obj_init.tools = deepcopy(obj.tools)
  5241. # drills are offset, so they need to be deep copied
  5242. obj_init.drills = deepcopy(obj.drills)
  5243. # slots are offset, so they need to be deep copied
  5244. obj_init.slots = deepcopy(obj.slots)
  5245. obj_init.create_geometry()
  5246. for obj in self.collection.get_selected():
  5247. obj_name = obj.options["name"]
  5248. try:
  5249. if isinstance(obj, FlatCAMExcellon):
  5250. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  5251. elif isinstance(obj, FlatCAMGerber):
  5252. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  5253. elif isinstance(obj, FlatCAMGeometry):
  5254. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  5255. except Exception as e:
  5256. return "Operation failed: %s" % str(e)
  5257. def on_copy_object2(self, custom_name):
  5258. def initialize_geometry(obj_init, app):
  5259. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5260. try:
  5261. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5262. except AttributeError:
  5263. pass
  5264. try:
  5265. obj_init.apertures = deepcopy(obj.apertures)
  5266. except AttributeError:
  5267. pass
  5268. try:
  5269. if obj.tools:
  5270. obj_init.tools = deepcopy(obj.tools)
  5271. except Exception as e:
  5272. log.debug("on_copy_object2() --> %s" % str(e))
  5273. def initialize_gerber(obj_init, app):
  5274. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5275. obj_init.apertures = deepcopy(obj.apertures)
  5276. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  5277. def initialize_excellon(obj_init, app):
  5278. obj_init.tools = deepcopy(obj.tools)
  5279. # drills are offset, so they need to be deep copied
  5280. obj_init.drills = deepcopy(obj.drills)
  5281. # slots are offset, so they need to be deep copied
  5282. obj_init.slots = deepcopy(obj.slots)
  5283. obj_init.create_geometry()
  5284. for obj in self.collection.get_selected():
  5285. obj_name = obj.options["name"]
  5286. try:
  5287. if isinstance(obj, FlatCAMExcellon):
  5288. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  5289. elif isinstance(obj, FlatCAMGerber):
  5290. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  5291. elif isinstance(obj, FlatCAMGeometry):
  5292. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  5293. except Exception as e:
  5294. return "Operation failed: %s" % str(e)
  5295. def on_rename_object(self, text):
  5296. self.report_usage("on_rename_object()")
  5297. named_obj = self.collection.get_active()
  5298. for obj in named_obj:
  5299. if obj is list:
  5300. self.on_rename_object(text)
  5301. else:
  5302. try:
  5303. obj.options['name'] = text
  5304. except Exception as e:
  5305. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  5306. def convert_any2geo(self):
  5307. self.report_usage("convert_any2geo()")
  5308. def initialize(obj_init, app):
  5309. obj_init.solid_geometry = obj.solid_geometry
  5310. try:
  5311. obj_init.follow_geometry = obj.follow_geometry
  5312. except AttributeError:
  5313. pass
  5314. try:
  5315. obj_init.apertures = obj.apertures
  5316. except AttributeError:
  5317. pass
  5318. try:
  5319. if obj.tools:
  5320. obj_init.tools = obj.tools
  5321. except AttributeError:
  5322. pass
  5323. def initialize_excellon(obj_init, app):
  5324. # objs = self.collection.get_selected()
  5325. # FlatCAMGeometry.merge(objs, obj)
  5326. solid_geo = []
  5327. for tool in obj.tools:
  5328. for geo in obj.tools[tool]['solid_geometry']:
  5329. solid_geo.append(geo)
  5330. obj_init.solid_geometry = deepcopy(solid_geo)
  5331. if not self.collection.get_selected():
  5332. log.warning("App.convert_any2geo --> No object selected")
  5333. self.inform.emit('[WARNING_NOTCL] %s' %
  5334. _("No object is selected. Select an object and try again."))
  5335. return
  5336. for obj in self.collection.get_selected():
  5337. obj_name = obj.options["name"]
  5338. try:
  5339. if isinstance(obj, FlatCAMExcellon):
  5340. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  5341. else:
  5342. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  5343. except Exception as e:
  5344. return "Operation failed: %s" % str(e)
  5345. def convert_any2gerber(self):
  5346. self.report_usage("convert_any2gerber()")
  5347. def initialize_geometry(obj_init, app):
  5348. apertures = {}
  5349. apid = 0
  5350. apertures[str(apid)] = {}
  5351. apertures[str(apid)]['geometry'] = []
  5352. for obj_orig in obj.solid_geometry:
  5353. new_elem = dict()
  5354. new_elem['solid'] = obj_orig
  5355. new_elem['follow'] = obj_orig.exterior
  5356. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  5357. apertures[str(apid)]['size'] = 0.0
  5358. apertures[str(apid)]['type'] = 'C'
  5359. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5360. obj_init.apertures = deepcopy(apertures)
  5361. def initialize_excellon(obj_init, app):
  5362. apertures = {}
  5363. apid = 10
  5364. for tool in obj.tools:
  5365. apertures[str(apid)] = {}
  5366. apertures[str(apid)]['geometry'] = []
  5367. for geo in obj.tools[tool]['solid_geometry']:
  5368. new_el = dict()
  5369. new_el['solid'] = geo
  5370. new_el['follow'] = geo.exterior
  5371. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  5372. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  5373. apertures[str(apid)]['type'] = 'C'
  5374. apid += 1
  5375. # create solid_geometry
  5376. solid_geometry = []
  5377. for apid in apertures:
  5378. for geo_el in apertures[apid]['geometry']:
  5379. solid_geometry.append(geo_el['solid'])
  5380. solid_geometry = MultiPolygon(solid_geometry)
  5381. solid_geometry = solid_geometry.buffer(0.0000001)
  5382. obj_init.solid_geometry = deepcopy(solid_geometry)
  5383. obj_init.apertures = deepcopy(apertures)
  5384. # clear the working objects (perhaps not necessary due of Python GC)
  5385. apertures.clear()
  5386. if not self.collection.get_selected():
  5387. log.warning("App.convert_any2gerber --> No object selected")
  5388. self.inform.emit('[WARNING_NOTCL] %s' %
  5389. _("No object is selected. Select an object and try again."))
  5390. return
  5391. for obj in self.collection.get_selected():
  5392. obj_name = obj.options["name"]
  5393. try:
  5394. if isinstance(obj, FlatCAMExcellon):
  5395. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  5396. elif isinstance(obj, FlatCAMGeometry):
  5397. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  5398. else:
  5399. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  5400. except Exception as e:
  5401. return "Operation failed: %s" % str(e)
  5402. def abort_all_tasks(self):
  5403. if self.abort_flag is False:
  5404. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  5405. self.abort_flag = True
  5406. def app_is_idle(self):
  5407. if self.abort_flag:
  5408. self.inform.emit('[WARNING_NOTCL] %s' %
  5409. _("The current task was gracefully closed on user request..."))
  5410. self.abort_flag = False
  5411. def on_selectall(self):
  5412. self.report_usage("on_selectall()")
  5413. # delete the possible selection box around a possible selected object
  5414. self.delete_selection_shape()
  5415. for name in self.collection.get_names():
  5416. self.collection.set_active(name)
  5417. curr_sel_obj = self.collection.get_by_name(name)
  5418. # create the selection box around the selected object
  5419. if self.defaults['global_selection_shape'] is True:
  5420. self.draw_selection_shape(curr_sel_obj)
  5421. def on_preferences(self):
  5422. # add the tab if it was closed
  5423. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  5424. # delete the absolute and relative position and messages in the infobar
  5425. self.ui.position_label.setText("")
  5426. self.ui.rel_position_label.setText("")
  5427. # Switch plot_area to preferences page
  5428. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  5429. # self.ui.show()
  5430. # this disconnect() is done so the slot will be connected only once
  5431. try:
  5432. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  5433. except (TypeError, AttributeError):
  5434. pass
  5435. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  5436. # detect changes in the preferences
  5437. for idx in range(self.ui.pref_tab_area.count()):
  5438. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5439. try:
  5440. try:
  5441. tb.textEdited.disconnect(self.on_preferences_edited)
  5442. except (TypeError, AttributeError):
  5443. pass
  5444. tb.textEdited.connect(self.on_preferences_edited)
  5445. except AttributeError:
  5446. pass
  5447. try:
  5448. try:
  5449. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5450. except (TypeError, AttributeError):
  5451. pass
  5452. tb.modificationChanged.connect(self.on_preferences_edited)
  5453. except AttributeError:
  5454. pass
  5455. try:
  5456. try:
  5457. tb.toggled.disconnect(self.on_preferences_edited)
  5458. except (TypeError, AttributeError):
  5459. pass
  5460. tb.toggled.connect(self.on_preferences_edited)
  5461. except AttributeError:
  5462. pass
  5463. try:
  5464. try:
  5465. tb.valueChanged.disconnect(self.on_preferences_edited)
  5466. except (TypeError, AttributeError):
  5467. pass
  5468. tb.valueChanged.connect(self.on_preferences_edited)
  5469. except AttributeError:
  5470. pass
  5471. try:
  5472. try:
  5473. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5474. except (TypeError, AttributeError):
  5475. pass
  5476. tb.currentIndexChanged.connect(self.on_preferences_edited)
  5477. except AttributeError:
  5478. pass
  5479. def on_preferences_edited(self):
  5480. self.inform.emit('[WARNING_NOTCL] %s' %
  5481. _("Preferences edited but not saved."))
  5482. self.preferences_changed_flag = True
  5483. def on_preferences_closed(self):
  5484. # disconnect
  5485. for idx in range(self.ui.pref_tab_area.count()):
  5486. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5487. try:
  5488. tb.textEdited.disconnect(self.on_preferences_edited)
  5489. except (TypeError, AttributeError):
  5490. pass
  5491. try:
  5492. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5493. except (TypeError, AttributeError):
  5494. pass
  5495. try:
  5496. tb.toggled.disconnect(self.on_preferences_edited)
  5497. except (TypeError, AttributeError):
  5498. pass
  5499. try:
  5500. tb.valueChanged.disconnect(self.on_preferences_edited)
  5501. except (TypeError, AttributeError):
  5502. pass
  5503. try:
  5504. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5505. except (TypeError, AttributeError):
  5506. pass
  5507. if self.preferences_changed_flag is True:
  5508. msgbox = QtWidgets.QMessageBox()
  5509. msgbox.setText(_("One or more values are changed.\n"
  5510. "Do you want to save the Preferences?"))
  5511. msgbox.setWindowTitle(_("Save Preferences"))
  5512. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  5513. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5514. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5515. msgbox.setDefaultButton(bt_yes)
  5516. msgbox.exec_()
  5517. response = msgbox.clickedButton()
  5518. if response == bt_yes:
  5519. self.on_save_button()
  5520. self.inform.emit('[success] %s' %
  5521. _("Preferences saved."))
  5522. else:
  5523. self.preferences_changed_flag = False
  5524. return
  5525. def on_flipy(self):
  5526. self.report_usage("on_flipy()")
  5527. obj_list = self.collection.get_selected()
  5528. xminlist = []
  5529. yminlist = []
  5530. xmaxlist = []
  5531. ymaxlist = []
  5532. if not obj_list:
  5533. self.inform.emit('[WARNING_NOTCL] %s' %
  5534. _("No object selected to Flip on Y axis."))
  5535. else:
  5536. try:
  5537. # first get a bounding box to fit all
  5538. for obj in obj_list:
  5539. xmin, ymin, xmax, ymax = obj.bounds()
  5540. xminlist.append(xmin)
  5541. yminlist.append(ymin)
  5542. xmaxlist.append(xmax)
  5543. ymaxlist.append(ymax)
  5544. # get the minimum x,y and maximum x,y for all objects selected
  5545. xminimal = min(xminlist)
  5546. yminimal = min(yminlist)
  5547. xmaximal = max(xmaxlist)
  5548. ymaximal = max(ymaxlist)
  5549. px = 0.5 * (xminimal + xmaximal)
  5550. py = 0.5 * (yminimal + ymaximal)
  5551. # execute mirroring
  5552. for obj in obj_list:
  5553. obj.mirror('X', [px, py])
  5554. obj.plot()
  5555. self.object_changed.emit(obj)
  5556. self.inform.emit('[success] %s' %
  5557. _("Flip on Y axis done."))
  5558. except Exception as e:
  5559. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5560. (_("Flip action was not executed."), str(e)))
  5561. return
  5562. def on_flipx(self):
  5563. self.report_usage("on_flipx()")
  5564. obj_list = self.collection.get_selected()
  5565. xminlist = []
  5566. yminlist = []
  5567. xmaxlist = []
  5568. ymaxlist = []
  5569. if not obj_list:
  5570. self.inform.emit('[WARNING_NOTCL] %s' %
  5571. _("No object selected to Flip on X axis."))
  5572. else:
  5573. try:
  5574. # first get a bounding box to fit all
  5575. for obj in obj_list:
  5576. xmin, ymin, xmax, ymax = obj.bounds()
  5577. xminlist.append(xmin)
  5578. yminlist.append(ymin)
  5579. xmaxlist.append(xmax)
  5580. ymaxlist.append(ymax)
  5581. # get the minimum x,y and maximum x,y for all objects selected
  5582. xminimal = min(xminlist)
  5583. yminimal = min(yminlist)
  5584. xmaximal = max(xmaxlist)
  5585. ymaximal = max(ymaxlist)
  5586. px = 0.5 * (xminimal + xmaximal)
  5587. py = 0.5 * (yminimal + ymaximal)
  5588. # execute mirroring
  5589. for obj in obj_list:
  5590. obj.mirror('Y', [px, py])
  5591. obj.plot()
  5592. self.object_changed.emit(obj)
  5593. self.inform.emit('[success] %s' %
  5594. _("Flip on X axis done."))
  5595. except Exception as e:
  5596. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5597. (_("Flip action was not executed."), str(e)))
  5598. return
  5599. def on_rotate(self, silent=False, preset=None):
  5600. self.report_usage("on_rotate()")
  5601. obj_list = self.collection.get_selected()
  5602. xminlist = []
  5603. yminlist = []
  5604. xmaxlist = []
  5605. ymaxlist = []
  5606. if not obj_list:
  5607. self.inform.emit('[WARNING_NOTCL] %s' %
  5608. _("No object selected to Rotate."))
  5609. else:
  5610. if silent is False:
  5611. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5612. min=-360, max=360, decimals=4,
  5613. init_val=float(self.defaults['tools_transform_rotate']))
  5614. num, ok = rotatebox.get_value()
  5615. else:
  5616. num = preset
  5617. ok = True
  5618. if ok:
  5619. try:
  5620. # first get a bounding box to fit all
  5621. for obj in obj_list:
  5622. xmin, ymin, xmax, ymax = obj.bounds()
  5623. xminlist.append(xmin)
  5624. yminlist.append(ymin)
  5625. xmaxlist.append(xmax)
  5626. ymaxlist.append(ymax)
  5627. # get the minimum x,y and maximum x,y for all objects selected
  5628. xminimal = min(xminlist)
  5629. yminimal = min(yminlist)
  5630. xmaximal = max(xmaxlist)
  5631. ymaximal = max(ymaxlist)
  5632. px = 0.5 * (xminimal + xmaximal)
  5633. py = 0.5 * (yminimal + ymaximal)
  5634. for sel_obj in obj_list:
  5635. sel_obj.rotate(-float(num), point=(px, py))
  5636. sel_obj.plot()
  5637. self.object_changed.emit(sel_obj)
  5638. self.inform.emit('[success] %s' %
  5639. _("Rotation done."))
  5640. except Exception as e:
  5641. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5642. (_("Rotation movement was not executed."), str(e)))
  5643. return
  5644. def on_skewx(self):
  5645. self.report_usage("on_skewx()")
  5646. obj_list = self.collection.get_selected()
  5647. xminlist = []
  5648. yminlist = []
  5649. if not obj_list:
  5650. self.inform.emit('[WARNING_NOTCL] %s' %
  5651. _("No object selected to Skew/Shear on X axis."))
  5652. else:
  5653. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5654. min=-360, max=360, decimals=4,
  5655. init_val=float(self.defaults['tools_transform_skew_x']))
  5656. num, ok = skewxbox.get_value()
  5657. if ok:
  5658. # first get a bounding box to fit all
  5659. for obj in obj_list:
  5660. xmin, ymin, xmax, ymax = obj.bounds()
  5661. xminlist.append(xmin)
  5662. yminlist.append(ymin)
  5663. # get the minimum x,y and maximum x,y for all objects selected
  5664. xminimal = min(xminlist)
  5665. yminimal = min(yminlist)
  5666. for obj in obj_list:
  5667. obj.skew(num, 0, point=(xminimal, yminimal))
  5668. obj.plot()
  5669. self.object_changed.emit(obj)
  5670. self.inform.emit('[success] %s' %
  5671. _("Skew on X axis done."))
  5672. def on_skewy(self):
  5673. self.report_usage("on_skewy()")
  5674. obj_list = self.collection.get_selected()
  5675. xminlist = []
  5676. yminlist = []
  5677. if not obj_list:
  5678. self.inform.emit('[WARNING_NOTCL] %s' %
  5679. _("No object selected to Skew/Shear on Y axis."))
  5680. else:
  5681. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5682. min=-360, max=360, decimals=4,
  5683. init_val=float(self.defaults['tools_transform_skew_y']))
  5684. num, ok = skewybox.get_value()
  5685. if ok:
  5686. # first get a bounding box to fit all
  5687. for obj in obj_list:
  5688. xmin, ymin, xmax, ymax = obj.bounds()
  5689. xminlist.append(xmin)
  5690. yminlist.append(ymin)
  5691. # get the minimum x,y and maximum x,y for all objects selected
  5692. xminimal = min(xminlist)
  5693. yminimal = min(yminlist)
  5694. for obj in obj_list:
  5695. obj.skew(0, num, point=(xminimal, yminimal))
  5696. obj.plot()
  5697. self.object_changed.emit(obj)
  5698. self.inform.emit('[success] %s' %
  5699. _("Skew on Y axis done."))
  5700. def on_plots_updated(self):
  5701. """
  5702. Callback used to report when the plots have changed.
  5703. Adjust axes and zooms to fit.
  5704. :return: None
  5705. """
  5706. self.plotcanvas.update() # TODO: Need update canvas?
  5707. self.on_zoom_fit(None)
  5708. self.collection.update_view()
  5709. # self.inform.emit(_("Plots updated ..."))
  5710. # TODO: Rework toolbar 'clear', 'replot' functions
  5711. def on_toolbar_replot(self):
  5712. """
  5713. Callback for toolbar button. Re-plots all objects.
  5714. :return: None
  5715. """
  5716. self.report_usage("on_toolbar_replot")
  5717. self.log.debug("on_toolbar_replot()")
  5718. try:
  5719. self.collection.get_active().read_form()
  5720. except AttributeError:
  5721. self.log.debug("on_toolbar_replot(): AttributeError")
  5722. pass
  5723. self.plot_all()
  5724. def on_row_activated(self, index):
  5725. if index.isValid():
  5726. if index.internalPointer().parent_item != self.collection.root_item:
  5727. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5728. self.collection.on_item_activated(index)
  5729. def grid_status(self):
  5730. if self.ui.grid_snap_btn.isChecked():
  5731. return True
  5732. else:
  5733. return False
  5734. def populate_cmenu_grids(self):
  5735. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5736. self.ui.cmenu_gridmenu.clear()
  5737. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5738. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  5739. grid_toggle.setCheckable(True)
  5740. if self.grid_status() == True:
  5741. grid_toggle.setChecked(True)
  5742. else:
  5743. grid_toggle.setChecked(False)
  5744. self.ui.cmenu_gridmenu.addSeparator()
  5745. for grid in sorted_list:
  5746. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  5747. action.triggered.connect(self.set_grid)
  5748. self.ui.cmenu_gridmenu.addSeparator()
  5749. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  5750. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  5751. grid_add.triggered.connect(self.on_grid_add)
  5752. grid_delete.triggered.connect(self.on_grid_delete)
  5753. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5754. def set_grid(self):
  5755. self.ui.grid_gap_x_entry.setText(self.sender().text())
  5756. self.ui.grid_gap_y_entry.setText(self.sender().text())
  5757. def on_grid_add(self):
  5758. # ## Current application units in lower Case
  5759. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5760. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5761. text=_('Enter a Grid Value:'),
  5762. min=0.0000, max=99.9999, decimals=4)
  5763. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  5764. val, ok = grid_add_popup.get_value()
  5765. if ok:
  5766. if float(val) == 0:
  5767. self.inform.emit('[WARNING_NOTCL] %s' %
  5768. _("Please enter a grid value with non-zero value, in Float format."))
  5769. return
  5770. else:
  5771. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5772. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5773. self.inform.emit('[success] %s...' %
  5774. _("New Grid added"))
  5775. else:
  5776. self.inform.emit('[WARNING_NOTCL] %s...' %
  5777. _("Grid already exists"))
  5778. else:
  5779. self.inform.emit('[WARNING_NOTCL] %s...' %
  5780. _("Adding New Grid cancelled"))
  5781. def on_grid_delete(self):
  5782. # ## Current application units in lower Case
  5783. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5784. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5785. text='Enter a Grid Value:',
  5786. min=0.0000, max=99.9999, decimals=4)
  5787. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  5788. val, ok = grid_del_popup.get_value()
  5789. if ok:
  5790. if float(val) == 0:
  5791. self.inform.emit('[WARNING_NOTCL] %s' %
  5792. _("Please enter a grid value with non-zero value, in Float format."))
  5793. return
  5794. else:
  5795. try:
  5796. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5797. except ValueError:
  5798. self.inform.emit('[ERROR_NOTCL]%s...' %
  5799. _(" Grid Value does not exist"))
  5800. return
  5801. self.inform.emit('[success] %s...' %
  5802. _("Grid Value deleted"))
  5803. else:
  5804. self.inform.emit('[WARNING_NOTCL] %s...' %
  5805. _("Delete Grid value cancelled"))
  5806. def on_shortcut_list(self):
  5807. self.report_usage("on_shortcut_list()")
  5808. # add the tab if it was closed
  5809. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5810. # delete the absolute and relative position and messages in the infobar
  5811. self.ui.position_label.setText("")
  5812. self.ui.rel_position_label.setText("")
  5813. # Switch plot_area to preferences page
  5814. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5815. # self.ui.show()
  5816. def on_select_tab(self, name):
  5817. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5818. if self.ui.splitter.sizes()[0] == 0:
  5819. self.ui.splitter.setSizes([1, 1])
  5820. else:
  5821. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5822. self.ui.splitter.setSizes([0, 1])
  5823. if name == 'project':
  5824. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5825. elif name == 'selected':
  5826. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5827. elif name == 'tool':
  5828. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5829. def on_copy_name(self):
  5830. self.report_usage("on_copy_name()")
  5831. obj = self.collection.get_active()
  5832. try:
  5833. name = obj.options["name"]
  5834. except AttributeError:
  5835. log.debug("on_copy_name() --> No object selected to copy it's name")
  5836. self.inform.emit('[WARNING_NOTCL]%s' %
  5837. _(" No object selected to copy it's name"))
  5838. return
  5839. self.clipboard.setText(name)
  5840. self.inform.emit(_("Name copied on clipboard ..."))
  5841. def on_mouse_click_over_plot(self, event):
  5842. """
  5843. Default actions are:
  5844. :param event: Contains information about the event, like which button
  5845. was clicked, the pixel coordinates and the axes coordinates.
  5846. :return: None
  5847. """
  5848. self.pos = []
  5849. # So it can receive key presses
  5850. self.plotcanvas.native.setFocus()
  5851. # Set the mouse button for panning
  5852. self.plotcanvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  5853. self.pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5854. if self.grid_status() == True:
  5855. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5856. self.app_cursor.enabled = True
  5857. else:
  5858. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5859. self.app_cursor.enabled = False
  5860. try:
  5861. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5862. if event.button == 1:
  5863. # Reset here the relative coordinates so there is a new reference on the click position
  5864. if self.rel_point1 is None:
  5865. self.rel_point1 = self.pos
  5866. else:
  5867. self.rel_point2 = copy(self.rel_point1)
  5868. self.rel_point1 = self.pos
  5869. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5870. if modifiers == QtCore.Qt.ShiftModifier:
  5871. # do not auto open the Project Tab
  5872. self.click_noproject = True
  5873. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  5874. self.inform.emit('[success] %s' %
  5875. _("Coordinates copied to clipboard."))
  5876. return
  5877. self.on_mouse_move_over_plot(event, origin_click=True)
  5878. except Exception as e:
  5879. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5880. def on_double_click_over_plot(self, event):
  5881. self.doubleclick = True
  5882. def on_mouse_move_over_plot(self, event, origin_click=None):
  5883. """
  5884. Callback for the mouse motion event over the plot.
  5885. :param event: Contains information about the event.
  5886. :param origin_click
  5887. :return: None
  5888. """
  5889. # So it can receive key presses
  5890. self.plotcanvas.native.setFocus()
  5891. self.pos_jump = event.pos
  5892. self.ui.popMenu.mouse_is_panning = False
  5893. if not origin_click:
  5894. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5895. if event.button == 2 and event.is_dragging == 1:
  5896. self.ui.popMenu.mouse_is_panning = True
  5897. return
  5898. if self.rel_point1 is not None:
  5899. try: # May fail in case mouse not within axes
  5900. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5901. if self.grid_status() == True:
  5902. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5903. self.app_cursor.enabled = True
  5904. # Update cursor
  5905. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  5906. else:
  5907. pos = (pos_canvas[0], pos_canvas[1])
  5908. self.app_cursor.enabled = False
  5909. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5910. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5911. dx = pos[0] - self.rel_point1[0]
  5912. dy = pos[1] - self.rel_point1[1]
  5913. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5914. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  5915. self.mouse = [pos[0], pos[1]]
  5916. # if the mouse is moved and the LMB is clicked then the action is a selection
  5917. if event.is_dragging == 1 and event.button == 1:
  5918. self.delete_selection_shape()
  5919. if dx < 0:
  5920. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5921. face_color=self.defaults['global_alt_sel_fill'])
  5922. self.selection_type = False
  5923. else:
  5924. self.draw_moving_selection_shape(self.pos, pos)
  5925. self.selection_type = True
  5926. # hover effect - enabled in Preferences -> General -> GUI Settings
  5927. if self.defaults['global_hover']:
  5928. for obj in self.collection.get_list():
  5929. try:
  5930. # select the object(s) only if it is enabled (plotted)
  5931. if obj.options['plot']:
  5932. if obj not in self.collection.get_selected():
  5933. poly_obj = Polygon(
  5934. [(obj.options['xmin'], obj.options['ymin']),
  5935. (obj.options['xmax'], obj.options['ymin']),
  5936. (obj.options['xmax'], obj.options['ymax']),
  5937. (obj.options['xmin'], obj.options['ymax'])]
  5938. )
  5939. if Point(pos).within(poly_obj):
  5940. if obj.isHovering is False:
  5941. obj.isHovering = True
  5942. obj.notHovering = True
  5943. # create the selection box around the selected object
  5944. self.draw_hover_shape(obj, color='#d1e0e0')
  5945. else:
  5946. if obj.notHovering is True:
  5947. obj.notHovering = False
  5948. obj.isHovering = False
  5949. self.delete_hover_shape()
  5950. except:
  5951. # the Exception here will happen if we try to select on screen and we have an
  5952. # newly (and empty) just created Geometry or Excellon object that do not have the
  5953. # xmin, xmax, ymin, ymax options.
  5954. # In this case poly_obj creation (see above) will fail
  5955. pass
  5956. except:
  5957. self.ui.position_label.setText("")
  5958. self.ui.rel_position_label.setText("")
  5959. self.mouse = None
  5960. def on_mouse_click_release_over_plot(self, event):
  5961. """
  5962. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5963. and has been registered in ''self.__init__()''.
  5964. :param event: contains information about the event.
  5965. :return:
  5966. """
  5967. pos = 0, 0
  5968. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5969. if self.grid_status() == True:
  5970. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5971. else:
  5972. pos = (pos_canvas[0], pos_canvas[1])
  5973. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5974. # canvas menu
  5975. if event.button == 2: # right click
  5976. if self.ui.popMenu.mouse_is_panning is False:
  5977. self.cursor = QtGui.QCursor()
  5978. self.populate_cmenu_grids()
  5979. self.ui.popMenu.popup(self.cursor.pos())
  5980. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5981. # selection and then select a type of selection ("enclosing" or "touching")
  5982. try:
  5983. if event.button == 1: # left click
  5984. if self.doubleclick is True:
  5985. self.doubleclick = False
  5986. if self.collection.get_selected():
  5987. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5988. if self.ui.splitter.sizes()[0] == 0:
  5989. self.ui.splitter.setSizes([1, 1])
  5990. # delete the selection shape(S) as it may be in the way
  5991. self.delete_selection_shape()
  5992. self.delete_hover_shape()
  5993. else:
  5994. if self.selection_type is not None:
  5995. self.selection_area_handler(self.pos, pos, self.selection_type)
  5996. self.selection_type = None
  5997. else:
  5998. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5999. if key_modifier == QtCore.Qt.ShiftModifier:
  6000. mod_key = 'Shift'
  6001. elif key_modifier == QtCore.Qt.ControlModifier:
  6002. mod_key = 'Control'
  6003. else:
  6004. mod_key = None
  6005. if mod_key == self.defaults["global_mselect_key"]:
  6006. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  6007. # deselect, and if it's not selected then it will be selected
  6008. # If there is no active command (self.command_active is None) then we check if we clicked
  6009. # on a object by checking the bounding limits against mouse click position
  6010. if self.command_active is None:
  6011. self.select_objects(key='CTRL')
  6012. self.delete_hover_shape()
  6013. else:
  6014. # If there is no active command (self.command_active is None) then we check if we clicked
  6015. # on a object by checking the bounding limits against mouse click position
  6016. if self.command_active is None:
  6017. self.select_objects()
  6018. self.delete_hover_shape()
  6019. except Exception as e:
  6020. log.warning("Error: %s" % str(e))
  6021. return
  6022. def selection_area_handler(self, start_pos, end_pos, sel_type):
  6023. """
  6024. :param start_pos: mouse position when the selection LMB click was done
  6025. :param end_pos: mouse position when the left mouse button is released
  6026. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  6027. :return:
  6028. """
  6029. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  6030. self.delete_selection_shape()
  6031. for obj in self.collection.get_list():
  6032. try:
  6033. # select the object(s) only if it is enabled (plotted)
  6034. if obj.options['plot']:
  6035. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  6036. (obj.options['xmax'], obj.options['ymin']),
  6037. (obj.options['xmax'], obj.options['ymax']),
  6038. (obj.options['xmin'], obj.options['ymax'])])
  6039. if sel_type is True:
  6040. if poly_obj.within(poly_selection):
  6041. # create the selection box around the selected object
  6042. if self.defaults['global_selection_shape'] is True:
  6043. self.draw_selection_shape(obj)
  6044. self.collection.set_active(obj.options['name'])
  6045. else:
  6046. if poly_selection.intersects(poly_obj):
  6047. # create the selection box around the selected object
  6048. if self.defaults['global_selection_shape'] is True:
  6049. self.draw_selection_shape(obj)
  6050. self.collection.set_active(obj.options['name'])
  6051. except Exception as e:
  6052. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  6053. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  6054. # In this case poly_obj creation (see above) will fail
  6055. log.debug("App.selection_area_handler() --> %s" % str(e))
  6056. def select_objects(self, key=None):
  6057. # list where we store the overlapped objects under our mouse left click position
  6058. objects_under_the_click_list = []
  6059. # Populate the list with the overlapped objects on the click position
  6060. curr_x, curr_y = self.pos
  6061. for obj in self.all_objects_list:
  6062. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  6063. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  6064. if obj.options['name'] not in objects_under_the_click_list:
  6065. if obj.options['plot']:
  6066. # add objects to the objects_under_the_click list only if the object is plotted
  6067. # (active and not disabled)
  6068. objects_under_the_click_list.append(obj.options['name'])
  6069. try:
  6070. # If there is no element in the overlapped objects list then make everyone inactive
  6071. # because we selected "nothing"
  6072. if not objects_under_the_click_list:
  6073. self.collection.set_all_inactive()
  6074. # delete the possible selection box around a possible selected object
  6075. self.delete_selection_shape()
  6076. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  6077. # only when working on App
  6078. if self.call_source == 'app':
  6079. if self.click_noproject is False:
  6080. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6081. else:
  6082. # restore auto open the Project Tab
  6083. self.click_noproject = False
  6084. # delete any text in the status bar, implicitly the last object name that was selected
  6085. self.inform.emit("")
  6086. else:
  6087. self.call_source = 'app'
  6088. else:
  6089. # case when there is only an object under the click and we toggle it
  6090. if len(objects_under_the_click_list) == 1:
  6091. if self.collection.get_active() is None:
  6092. self.collection.set_active(objects_under_the_click_list[0])
  6093. # create the selection box around the selected object
  6094. curr_sel_obj = self.collection.get_active()
  6095. if self.defaults['global_selection_shape'] is True:
  6096. self.draw_selection_shape(curr_sel_obj)
  6097. # self.inform.emit('[selected] %s: %s selected' %
  6098. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6099. if curr_sel_obj.kind == 'gerber':
  6100. self.inform.emit(
  6101. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6102. color='green', name=str(curr_sel_obj.options['name'])))
  6103. elif curr_sel_obj.kind == 'excellon':
  6104. self.inform.emit(
  6105. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6106. color='brown', name=str(curr_sel_obj.options['name'])))
  6107. elif curr_sel_obj.kind == 'cncjob':
  6108. self.inform.emit(
  6109. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6110. color='blue', name=str(curr_sel_obj.options['name'])))
  6111. elif curr_sel_obj.kind == 'geometry':
  6112. self.inform.emit(
  6113. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6114. color='red', name=str(curr_sel_obj.options['name'])))
  6115. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  6116. self.collection.set_all_inactive()
  6117. self.delete_selection_shape()
  6118. self.collection.set_active(objects_under_the_click_list[0])
  6119. # create the selection box around the selected object
  6120. curr_sel_obj = self.collection.get_active()
  6121. if self.defaults['global_selection_shape'] is True:
  6122. self.draw_selection_shape(curr_sel_obj)
  6123. # self.inform.emit('[selected] %s: %s selected' %
  6124. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6125. if curr_sel_obj.kind == 'gerber':
  6126. self.inform.emit(
  6127. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6128. color='green', name=str(curr_sel_obj.options['name'])))
  6129. elif curr_sel_obj.kind == 'excellon':
  6130. self.inform.emit(
  6131. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6132. color='brown', name=str(curr_sel_obj.options['name'])))
  6133. elif curr_sel_obj.kind == 'cncjob':
  6134. self.inform.emit(
  6135. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6136. color='blue', name=str(curr_sel_obj.options['name'])))
  6137. elif curr_sel_obj.kind == 'geometry':
  6138. self.inform.emit(
  6139. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6140. color='red', name=str(curr_sel_obj.options['name'])))
  6141. else:
  6142. self.collection.set_all_inactive()
  6143. self.delete_selection_shape()
  6144. if self.call_source == 'app':
  6145. # delete any text in the status bar, implicitly the last object name that was selected
  6146. self.inform.emit("")
  6147. else:
  6148. self.call_source = 'app'
  6149. else:
  6150. # If there is no selected object
  6151. # make active the first element of the overlapped objects list
  6152. if self.collection.get_active() is None:
  6153. self.collection.set_active(objects_under_the_click_list[0])
  6154. name_sel_obj = self.collection.get_active().options['name']
  6155. # In case that there is a selected object but it is not in the overlapped object list
  6156. # make that object inactive and activate the first element in the overlapped object list
  6157. if name_sel_obj not in objects_under_the_click_list:
  6158. self.collection.set_inactive(name_sel_obj)
  6159. name_sel_obj = objects_under_the_click_list[0]
  6160. self.collection.set_active(name_sel_obj)
  6161. else:
  6162. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  6163. self.collection.set_all_inactive()
  6164. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  6165. len(objects_under_the_click_list)])
  6166. curr_sel_obj = self.collection.get_active()
  6167. # delete the possible selection box around a possible selected object
  6168. self.delete_selection_shape()
  6169. # create the selection box around the selected object
  6170. if self.defaults['global_selection_shape'] is True:
  6171. self.draw_selection_shape(curr_sel_obj)
  6172. # self.inform.emit('[selected] %s: %s selected' %
  6173. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6174. if curr_sel_obj.kind == 'gerber':
  6175. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6176. color='green', name=str(curr_sel_obj.options['name'])))
  6177. elif curr_sel_obj.kind == 'excellon':
  6178. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6179. color='brown', name=str(curr_sel_obj.options['name'])))
  6180. elif curr_sel_obj.kind == 'cncjob':
  6181. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6182. color='blue', name=str(curr_sel_obj.options['name'])))
  6183. elif curr_sel_obj.kind == 'geometry':
  6184. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6185. color='red', name=str(curr_sel_obj.options['name'])))
  6186. # for obj in self.collection.get_list():
  6187. # obj.plot()
  6188. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  6189. # TODO: on selected objects change the object colors and do not draw the selection box
  6190. # self.plotcanvas.update() # this updates the canvas
  6191. except Exception as e:
  6192. log.error("[ERROR] Something went bad. %s" % str(e))
  6193. return
  6194. def delete_hover_shape(self):
  6195. self.hover_shapes.clear()
  6196. self.hover_shapes.redraw()
  6197. def draw_hover_shape(self, sel_obj, color=None):
  6198. """
  6199. :param sel_obj: the object for which the hover shape must be drawn
  6200. :return:
  6201. """
  6202. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6203. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6204. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6205. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6206. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  6207. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6208. hover_rect = hover_rect.buffer(-0.1)
  6209. hover_rect = hover_rect.buffer(0.2)
  6210. else:
  6211. hover_rect = hover_rect.buffer(-0.00393)
  6212. hover_rect = hover_rect.buffer(0.00787)
  6213. if color:
  6214. face = Color(color)
  6215. face.alpha = 0.2
  6216. outline = Color(color, alpha=0.8)
  6217. else:
  6218. face = Color(self.defaults['global_sel_fill'])
  6219. face.alpha = 0.2
  6220. outline = self.defaults['global_sel_line']
  6221. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  6222. def delete_selection_shape(self):
  6223. self.move_tool.sel_shapes.clear()
  6224. self.move_tool.sel_shapes.redraw()
  6225. def draw_selection_shape(self, sel_obj, color=None):
  6226. """
  6227. :param sel_obj: the object for which the selection shape must be drawn
  6228. :return:
  6229. """
  6230. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6231. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6232. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6233. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6234. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6235. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6236. sel_rect = sel_rect.buffer(-0.1)
  6237. sel_rect = sel_rect.buffer(0.2)
  6238. else:
  6239. sel_rect = sel_rect.buffer(-0.00393)
  6240. sel_rect = sel_rect.buffer(0.00787)
  6241. if color:
  6242. face = Color(color, alpha=0.2)
  6243. outline = Color(color, alpha=0.8)
  6244. else:
  6245. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  6246. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  6247. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6248. color=outline,
  6249. face_color=face,
  6250. update=True,
  6251. layer=0,
  6252. tolerance=None))
  6253. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  6254. """
  6255. :param old_coords: old coordinates
  6256. :param coords: new coordinates
  6257. :return:
  6258. """
  6259. if 'color' in kwargs:
  6260. color = kwargs['color']
  6261. else:
  6262. color = self.defaults['global_sel_line']
  6263. if 'face_color' in kwargs:
  6264. face_color = kwargs['face_color']
  6265. else:
  6266. face_color = self.defaults['global_sel_fill']
  6267. if 'face_alpha' in kwargs:
  6268. face_alpha = kwargs['face_alpha']
  6269. else:
  6270. face_alpha = 0.3
  6271. x0, y0 = old_coords
  6272. x1, y1 = coords
  6273. pt1 = (x0, y0)
  6274. pt2 = (x1, y0)
  6275. pt3 = (x1, y1)
  6276. pt4 = (x0, y1)
  6277. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6278. color_t = Color(face_color)
  6279. color_t.alpha = face_alpha
  6280. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  6281. layer=0, tolerance=None)
  6282. def on_file_new_click(self):
  6283. if self.collection.get_list() and self.should_we_save:
  6284. msgbox = QtWidgets.QMessageBox()
  6285. # msgbox.setText("<B>Save changes ...</B>")
  6286. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6287. "Creating a New project will delete them.\n"
  6288. "Do you want to Save the project?"))
  6289. msgbox.setWindowTitle(_("Save changes"))
  6290. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6291. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6292. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6293. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6294. msgbox.setDefaultButton(bt_yes)
  6295. msgbox.exec_()
  6296. response = msgbox.clickedButton()
  6297. if response == bt_yes:
  6298. self.on_file_saveprojectas()
  6299. elif response == bt_cancel:
  6300. return
  6301. elif response == bt_no:
  6302. self.on_file_new()
  6303. else:
  6304. self.on_file_new()
  6305. self.inform.emit('[success] %s...' %
  6306. _("New Project created"))
  6307. def on_file_new(self):
  6308. """
  6309. Callback for menu item File->New. Returns the application to its
  6310. startup state. This method is thread-safe.
  6311. :return: None
  6312. """
  6313. self.report_usage("on_file_new")
  6314. # Remove everything from memory
  6315. App.log.debug("on_file_new()")
  6316. if self.call_source != 'app':
  6317. self.editor2object(cleanup=True)
  6318. # ## EDITOR section
  6319. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  6320. self.exc_editor = FlatCAMExcEditor(self)
  6321. self.grb_editor = FlatCAMGrbEditor(self)
  6322. # Clear pool
  6323. self.clear_pool()
  6324. for obj in self.collection.get_list():
  6325. # delete shapes left drawn from mark shape_collections, if any
  6326. if isinstance(obj, FlatCAMGerber):
  6327. try:
  6328. obj.mark_shapes.enabled = False
  6329. obj.mark_shapes.clear(update=True)
  6330. except AttributeError:
  6331. pass
  6332. # also delete annotation shapes, if any
  6333. elif isinstance(obj, FlatCAMCNCjob):
  6334. try:
  6335. obj.annotation.enabled = False
  6336. obj.annotation.clear(update=True)
  6337. except AttributeError:
  6338. pass
  6339. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6340. self.init_tcl()
  6341. self.delete_selection_shape()
  6342. self.collection.delete_all()
  6343. self.setup_component_editor()
  6344. # Clear project filename
  6345. self.project_filename = None
  6346. # Load the application defaults
  6347. self.load_defaults(filename='current_defaults')
  6348. # Re-fresh project options
  6349. self.on_options_app2project()
  6350. # Init Tools
  6351. self.init_tools()
  6352. # Close any Tabs opened in the Plot Tab Area section
  6353. for index in range(self.ui.plot_tab_area.count()):
  6354. self.ui.plot_tab_area.closeTab(index)
  6355. # for whatever reason previous command does not close the last tab so I do it manually
  6356. self.ui.plot_tab_area.closeTab(0)
  6357. # # And then add again the Plot Area
  6358. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  6359. self.ui.plot_tab_area.protectTab(0)
  6360. # take the focus of the Notebook on Project Tab.
  6361. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6362. self.set_ui_title(name=_("New Project - Not saved"))
  6363. def obj_properties(self):
  6364. self.report_usage("obj_properties()")
  6365. self.properties_tool.run(toggle=False)
  6366. def on_project_context_save(self):
  6367. obj = self.collection.get_active()
  6368. if type(obj) == FlatCAMGeometry:
  6369. self.on_file_exportdxf()
  6370. elif type(obj) == FlatCAMExcellon:
  6371. self.on_file_saveexcellon()
  6372. elif type(obj) == FlatCAMCNCjob:
  6373. obj.on_exportgcode_button_click()
  6374. elif type(obj) == FlatCAMGerber:
  6375. self.on_file_savegerber()
  6376. def obj_move(self):
  6377. self.report_usage("obj_move()")
  6378. self.move_tool.run(toggle=False)
  6379. def on_fileopengerber(self, checked=None, name=None):
  6380. """
  6381. File menu callback for opening a Gerber.
  6382. :return: None
  6383. """
  6384. self.report_usage("on_fileopengerber")
  6385. App.log.debug("on_fileopengerber()")
  6386. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6387. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6388. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  6389. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6390. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6391. "*.mil);;" \
  6392. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6393. "Allegro Files (*.art);;" \
  6394. "Mentor Files (*.pho *.gdo);;" \
  6395. "All Files (*.*)"
  6396. if name is None:
  6397. try:
  6398. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6399. directory=self.get_last_folder(),
  6400. filter=_filter_)
  6401. except TypeError:
  6402. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6403. filenames = [str(filename) for filename in filenames]
  6404. else:
  6405. filenames = [name]
  6406. if len(filenames) == 0:
  6407. self.inform.emit('[WARNING_NOTCL] %s' %
  6408. _("Open Gerber cancelled."))
  6409. else:
  6410. for filename in filenames:
  6411. if filename != '':
  6412. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6413. def on_fileopenexcellon(self, checked=None, name=None):
  6414. """
  6415. File menu callback for opening an Excellon file.
  6416. :return: None
  6417. """
  6418. self.report_usage("on_fileopenexcellon")
  6419. App.log.debug("on_fileopenexcellon()")
  6420. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6421. "All Files (*.*)"
  6422. if name is None:
  6423. try:
  6424. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6425. directory=self.get_last_folder(),
  6426. filter=_filter_)
  6427. except TypeError:
  6428. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6429. filenames = [str(filename) for filename in filenames]
  6430. else:
  6431. filenames = [str(name)]
  6432. if len(filenames) == 0:
  6433. self.inform.emit('[WARNING_NOTCL]%s' %
  6434. _(" Open Excellon cancelled."))
  6435. else:
  6436. for filename in filenames:
  6437. if filename != '':
  6438. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6439. def on_fileopengcode(self, checked=None, name=None):
  6440. """
  6441. File menu call back for opening gcode.
  6442. :return: None
  6443. """
  6444. self.report_usage("on_fileopengcode")
  6445. App.log.debug("on_fileopengcode()")
  6446. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6447. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6448. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  6449. "All Files (*.*)"
  6450. if name is None:
  6451. try:
  6452. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6453. directory=self.get_last_folder(),
  6454. filter=_filter_)
  6455. except TypeError:
  6456. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6457. filenames = [str(filename) for filename in filenames]
  6458. else:
  6459. filenames = [name]
  6460. if len(filenames) == 0:
  6461. self.inform.emit('[WARNING_NOTCL] %s' %
  6462. _("Open G-Code cancelled."))
  6463. else:
  6464. for filename in filenames:
  6465. if filename != '':
  6466. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename]})
  6467. def on_file_openproject(self, checked=None):
  6468. """
  6469. File menu callback for opening a project.
  6470. :return: None
  6471. """
  6472. self.report_usage("on_file_openproject")
  6473. App.log.debug("on_file_openproject()")
  6474. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6475. try:
  6476. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6477. directory=self.get_last_folder(), filter=_filter_)
  6478. except TypeError:
  6479. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6480. # The Qt methods above will return a QString which can cause problems later.
  6481. # So far json.dump() will fail to serialize it.
  6482. # TODO: Improve the serialization methods and remove this fix.
  6483. filename = str(filename)
  6484. if filename == "":
  6485. self.inform.emit('[WARNING_NOTCL] %s' %
  6486. _("Open Project cancelled."))
  6487. else:
  6488. # self.worker_task.emit({'fcn': self.open_project,
  6489. # 'params': [filename]})
  6490. # The above was failing because open_project() is not
  6491. # thread safe. The new_project()
  6492. self.open_project(filename)
  6493. def on_file_openconfig(self, checked=None):
  6494. """
  6495. File menu callback for opening a config file.
  6496. :return: None
  6497. """
  6498. self.report_usage("on_file_openconfig")
  6499. App.log.debug("on_file_openconfig()")
  6500. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6501. try:
  6502. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6503. directory=self.data_path, filter=_filter_)
  6504. except TypeError:
  6505. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6506. filter=_filter_)
  6507. if filename == "":
  6508. self.inform.emit('[WARNING_NOTCL] %s' %
  6509. _("Open Config cancelled."))
  6510. else:
  6511. self.open_config_file(filename)
  6512. def on_file_exportsvg(self):
  6513. """
  6514. Callback for menu item File->Export SVG.
  6515. :return: None
  6516. """
  6517. self.report_usage("on_file_exportsvg")
  6518. App.log.debug("on_file_exportsvg()")
  6519. obj = self.collection.get_active()
  6520. if obj is None:
  6521. self.inform.emit('[WARNING_NOTCL] %s' %
  6522. _("No object selected."))
  6523. msg = _("Please Select a Geometry object to export")
  6524. msgbox = QtWidgets.QMessageBox()
  6525. msgbox.setInformativeText(msg)
  6526. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6527. msgbox.setDefaultButton(bt_ok)
  6528. msgbox.exec_()
  6529. return
  6530. # Check for more compatible types and add as required
  6531. if (not isinstance(obj, FlatCAMGeometry)
  6532. and not isinstance(obj, FlatCAMGerber)
  6533. and not isinstance(obj, FlatCAMCNCjob)
  6534. and not isinstance(obj, FlatCAMExcellon)):
  6535. msg = '[ERROR_NOTCL] %s' % \
  6536. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6537. msgbox = QtWidgets.QMessageBox()
  6538. msgbox.setInformativeText(msg)
  6539. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6540. msgbox.setDefaultButton(bt_ok)
  6541. msgbox.exec_()
  6542. return
  6543. name = obj.options["name"]
  6544. _filter = "SVG File (*.svg);;All Files (*.*)"
  6545. try:
  6546. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6547. caption=_("Export SVG"),
  6548. directory=self.get_last_save_folder() + '/' + str(name),
  6549. filter=_filter)
  6550. except TypeError:
  6551. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  6552. filename = str(filename)
  6553. if filename == "":
  6554. self.inform.emit('[WARNING_NOTCL]%s' %
  6555. _(" Export SVG cancelled."))
  6556. return
  6557. else:
  6558. self.export_svg(name, filename)
  6559. if self.defaults["global_open_style"] is False:
  6560. self.file_opened.emit("SVG", filename)
  6561. self.file_saved.emit("SVG", filename)
  6562. def on_file_exportpng(self):
  6563. self.report_usage("on_file_exportpng")
  6564. App.log.debug("on_file_exportpng()")
  6565. self.date = str(datetime.today()).rpartition('.')[0]
  6566. self.date = ''.join(c for c in self.date if c not in ':-')
  6567. self.date = self.date.replace(' ', '_')
  6568. image = _screenshot()
  6569. data = np.asarray(image)
  6570. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6571. self.inform.emit('[[WARNING_NOTCL]] %s' %
  6572. _('Data must be a 3D array with last dimension 3 or 4'))
  6573. return
  6574. filter_ = "PNG File (*.png);;All Files (*.*)"
  6575. try:
  6576. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6577. caption=_("Export PNG Image"),
  6578. directory=self.get_last_save_folder() + '/png_' + self.date,
  6579. filter=filter_)
  6580. except TypeError:
  6581. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  6582. filename = str(filename)
  6583. if filename == "":
  6584. self.inform.emit(_("Export PNG cancelled."))
  6585. return
  6586. else:
  6587. write_png(filename, data)
  6588. if self.defaults["global_open_style"] is False:
  6589. self.file_opened.emit("png", filename)
  6590. self.file_saved.emit("png", filename)
  6591. def on_file_savegerber(self):
  6592. """
  6593. Callback for menu item in Project context menu.
  6594. :return: None
  6595. """
  6596. self.report_usage("on_file_savegerber")
  6597. App.log.debug("on_file_savegerber()")
  6598. obj = self.collection.get_active()
  6599. if obj is None:
  6600. self.inform.emit('[WARNING_NOTCL] %s' %
  6601. _("No object selected. Please select an Gerber object to export."))
  6602. return
  6603. # Check for more compatible types and add as required
  6604. if not isinstance(obj, FlatCAMGerber):
  6605. self.inform.emit('[ERROR_NOTCL] %s' %
  6606. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6607. return
  6608. name = self.collection.get_active().options["name"]
  6609. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6610. try:
  6611. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6612. caption="Save Gerber source file",
  6613. directory=self.get_last_save_folder() + '/' + name,
  6614. filter=_filter)
  6615. except TypeError:
  6616. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  6617. filename = str(filename)
  6618. if filename == "":
  6619. self.inform.emit('[WARNING_NOTCL] %s' %
  6620. _("Save Gerber source file cancelled."))
  6621. return
  6622. else:
  6623. self.save_source_file(name, filename)
  6624. if self.defaults["global_open_style"] is False:
  6625. self.file_opened.emit("Gerber", filename)
  6626. self.file_saved.emit("Gerber", filename)
  6627. def on_file_saveexcellon(self):
  6628. """
  6629. Callback for menu item in project context menu.
  6630. :return: None
  6631. """
  6632. self.report_usage("on_file_saveexcellon")
  6633. App.log.debug("on_file_saveexcellon()")
  6634. obj = self.collection.get_active()
  6635. if obj is None:
  6636. self.inform.emit('[WARNING_NOTCL] %s' %
  6637. _("No object selected. Please select an Excellon object to export."))
  6638. return
  6639. # Check for more compatible types and add as required
  6640. if not isinstance(obj, FlatCAMExcellon):
  6641. self.inform.emit('[ERROR_NOTCL] %s' %
  6642. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6643. return
  6644. name = self.collection.get_active().options["name"]
  6645. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6646. try:
  6647. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6648. caption=_("Save Excellon source file"),
  6649. directory=self.get_last_save_folder() + '/' + name,
  6650. filter=_filter)
  6651. except TypeError:
  6652. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  6653. filename = str(filename)
  6654. if filename == "":
  6655. self.inform.emit('[WARNING_NOTCL] %s' %
  6656. _("Saving Excellon source file cancelled."))
  6657. return
  6658. else:
  6659. self.save_source_file(name, filename)
  6660. if self.defaults["global_open_style"] is False:
  6661. self.file_opened.emit("Excellon", filename)
  6662. self.file_saved.emit("Excellon", filename)
  6663. def on_file_exportexcellon(self):
  6664. """
  6665. Callback for menu item File->Export->Excellon.
  6666. :return: None
  6667. """
  6668. self.report_usage("on_file_exportexcellon")
  6669. App.log.debug("on_file_exportexcellon()")
  6670. obj = self.collection.get_active()
  6671. if obj is None:
  6672. self.inform.emit('[WARNING_NOTCL] %s' %
  6673. _("No object selected. Please Select an Excellon object to export."))
  6674. return
  6675. # Check for more compatible types and add as required
  6676. if not isinstance(obj, FlatCAMExcellon):
  6677. self.inform.emit('[ERROR_NOTCL] %s' %
  6678. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6679. return
  6680. name = self.collection.get_active().options["name"]
  6681. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6682. try:
  6683. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6684. caption=_("Export Excellon"),
  6685. directory=self.get_last_save_folder() + '/' + name,
  6686. filter=_filter)
  6687. except TypeError:
  6688. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  6689. filename = str(filename)
  6690. if filename == "":
  6691. self.inform.emit('[WARNING_NOTCL] %s' %
  6692. _("Export Excellon cancelled."))
  6693. return
  6694. else:
  6695. self.export_excellon(name, filename)
  6696. if self.defaults["global_open_style"] is False:
  6697. self.file_opened.emit("Excellon", filename)
  6698. self.file_saved.emit("Excellon", filename)
  6699. def on_file_exportgerber(self):
  6700. """
  6701. Callback for menu item File->Export->Gerber.
  6702. :return: None
  6703. """
  6704. self.report_usage("on_file_exportgerber")
  6705. App.log.debug("on_file_exportgerber()")
  6706. obj = self.collection.get_active()
  6707. if obj is None:
  6708. self.inform.emit('[WARNING_NOTCL] %s' %
  6709. _("No object selected. Please Select an Gerber object to export."))
  6710. return
  6711. # Check for more compatible types and add as required
  6712. if not isinstance(obj, FlatCAMGerber):
  6713. self.inform.emit('[ERROR_NOTCL] %s' %
  6714. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6715. return
  6716. name = self.collection.get_active().options["name"]
  6717. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  6718. try:
  6719. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6720. caption=_("Export Gerber"),
  6721. directory=self.get_last_save_folder() + '/' + name,
  6722. filter=_filter_)
  6723. except TypeError:
  6724. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  6725. filename = str(filename)
  6726. if filename == "":
  6727. self.inform.emit('[WARNING_NOTCL] %s' %
  6728. _("Export Gerber cancelled."))
  6729. return
  6730. else:
  6731. self.export_gerber(name, filename)
  6732. if self.defaults["global_open_style"] is False:
  6733. self.file_opened.emit("Gerber", filename)
  6734. self.file_saved.emit("Gerber", filename)
  6735. def on_file_exportdxf(self):
  6736. """
  6737. Callback for menu item File->Export DXF.
  6738. :return: None
  6739. """
  6740. self.report_usage("on_file_exportdxf")
  6741. App.log.debug("on_file_exportdxf()")
  6742. obj = self.collection.get_active()
  6743. if obj is None:
  6744. self.inform.emit('[WARNING_NOTCL] %s' %
  6745. _("No object selected."))
  6746. msg = _("Please Select a Geometry object to export")
  6747. msgbox = QtWidgets.QMessageBox()
  6748. msgbox.setInformativeText(msg)
  6749. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6750. msgbox.setDefaultButton(bt_ok)
  6751. msgbox.exec_()
  6752. return
  6753. # Check for more compatible types and add as required
  6754. if not isinstance(obj, FlatCAMGeometry):
  6755. msg = '[ERROR_NOTCL] %s' % \
  6756. _("Only Geometry objects can be used.")
  6757. msgbox = QtWidgets.QMessageBox()
  6758. msgbox.setInformativeText(msg)
  6759. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6760. msgbox.setDefaultButton(bt_ok)
  6761. msgbox.exec_()
  6762. return
  6763. name = self.collection.get_active().options["name"]
  6764. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  6765. try:
  6766. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6767. caption=_("Export DXF"),
  6768. directory=self.get_last_save_folder() + '/' + name,
  6769. filter=_filter_)
  6770. except TypeError:
  6771. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  6772. filter=_filter_)
  6773. filename = str(filename)
  6774. if filename == "":
  6775. self.inform.emit('[WARNING_NOTCL] %s' %
  6776. _("Export DXF cancelled."))
  6777. return
  6778. else:
  6779. self.export_dxf(name, filename)
  6780. if self.defaults["global_open_style"] is False:
  6781. self.file_opened.emit("DXF", filename)
  6782. self.file_saved.emit("DXF", filename)
  6783. def on_file_importsvg(self, type_of_obj):
  6784. """
  6785. Callback for menu item File->Import SVG.
  6786. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6787. :type type_of_obj: str
  6788. :return: None
  6789. """
  6790. self.report_usage("on_file_importsvg")
  6791. App.log.debug("on_file_importsvg()")
  6792. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  6793. try:
  6794. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6795. directory=self.get_last_folder(), filter=_filter_)
  6796. except TypeError:
  6797. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6798. filter=_filter_)
  6799. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  6800. type_of_obj = "geometry"
  6801. filenames = [str(filename) for filename in filenames]
  6802. if len(filenames) == 0:
  6803. self.inform.emit('[WARNING_NOTCL] %s' %
  6804. _("Open SVG cancelled."))
  6805. else:
  6806. for filename in filenames:
  6807. if filename != '':
  6808. self.worker_task.emit({'fcn': self.import_svg,
  6809. 'params': [filename, type_of_obj]})
  6810. def on_file_importdxf(self, type_of_obj):
  6811. """
  6812. Callback for menu item File->Import DXF.
  6813. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6814. :type type_of_obj: str
  6815. :return: None
  6816. """
  6817. self.report_usage("on_file_importdxf")
  6818. App.log.debug("on_file_importdxf()")
  6819. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  6820. try:
  6821. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6822. directory=self.get_last_folder(),
  6823. filter=_filter_)
  6824. except TypeError:
  6825. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6826. filter=_filter_)
  6827. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  6828. type_of_obj = "geometry"
  6829. filenames = [str(filename) for filename in filenames]
  6830. if len(filenames) == 0:
  6831. self.inform.emit('[WARNING_NOTCL] %s' %
  6832. _("Open DXF cancelled."))
  6833. else:
  6834. for filename in filenames:
  6835. if filename != '':
  6836. self.worker_task.emit({'fcn': self.import_dxf,
  6837. 'params': [filename, type_of_obj]})
  6838. # ###############################################################################################################
  6839. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6840. # ###############################################################################################################
  6841. def init_code_editor(self, name):
  6842. # Signals section
  6843. # Disconnect the old signals
  6844. try:
  6845. self.ui.buttonOpen.clicked.disconnect()
  6846. except TypeError:
  6847. pass
  6848. try:
  6849. self.ui.buttonSave.clicked.disconnect()
  6850. except TypeError:
  6851. pass
  6852. # add the tab if it was closed
  6853. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, '%s' % name)
  6854. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  6855. # delete the absolute and relative position and messages in the infobar
  6856. self.ui.position_label.setText("")
  6857. self.ui.rel_position_label.setText("")
  6858. # first clear previous text in text editor (if any)
  6859. self.ui.code_editor.clear()
  6860. self.ui.code_editor.setReadOnly(False)
  6861. self.toggle_codeeditor = True
  6862. self.ui.code_editor.completer_enable = False
  6863. self.ui.buttonRun.hide()
  6864. # Switch plot_area to CNCJob tab
  6865. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  6866. def on_view_source(self):
  6867. self.inform.emit('%s' %
  6868. _("Viewing the source code of the selected object."))
  6869. self.proc_container.view.set_busy(_("Loading..."))
  6870. try:
  6871. obj = self.collection.get_active()
  6872. except Exception as e:
  6873. log.debug("App.on_view_source() --> %s" % str(e))
  6874. self.inform.emit('[WARNING_NOTCL] %s' %
  6875. _("Select an Gerber or Excellon file to view it's source file."))
  6876. return 'fail'
  6877. if obj.kind == 'gerber':
  6878. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  6879. else:
  6880. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  6881. self.init_code_editor(name=_("Source Editor"))
  6882. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  6883. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  6884. # then append the text from GCode to the text editor
  6885. try:
  6886. file = StringIO(obj.source_file)
  6887. except AttributeError:
  6888. self.inform.emit('[WARNING_NOTCL] %s' %
  6889. _("There is no selected object for which to see it's source file code."))
  6890. return 'fail'
  6891. self.ui.cncjob_frame.hide()
  6892. try:
  6893. for line in file:
  6894. QtWidgets.QApplication.processEvents()
  6895. proc_line = str(line).strip('\n')
  6896. self.ui.code_editor.append(proc_line)
  6897. except Exception as e:
  6898. log.debug('App.on_view_source() -->%s' % str(e))
  6899. self.inform.emit('[ERROR] %s: %s' %
  6900. (_('Failed to load the source code for the selected object'), str(e)))
  6901. return
  6902. self.handleTextChanged()
  6903. self.ui.cncjob_frame.show()
  6904. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6905. self.proc_container.view.set_idle()
  6906. # self.ui.show()
  6907. def on_toggle_code_editor(self):
  6908. self.report_usage("on_toggle_code_editor()")
  6909. if self.toggle_codeeditor is False:
  6910. self.init_code_editor(name=_("Code Editor"))
  6911. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  6912. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  6913. else:
  6914. for idx in range(self.ui.plot_tab_area.count()):
  6915. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  6916. self.ui.plot_tab_area.closeTab(idx)
  6917. break
  6918. self.toggle_codeeditor = False
  6919. def on_filenewscript(self):
  6920. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6921. self.init_code_editor(name=_("Script Editor"))
  6922. self.ui.code_editor.completer_enable = True
  6923. self.ui.code_editor.append(_(
  6924. "#\n"
  6925. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  6926. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  6927. "#\n\n"
  6928. "# FlatCAM commands list:\n"
  6929. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, ClearCopper,\n"
  6930. "# Cncjob, Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames,\n"
  6931. "# GetSys, ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillDrills,\n"
  6932. "# MillSlots, Mirror, New, NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"
  6933. "# Options, Paint, Panelize, Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,\n"
  6934. "# SubtractRectangle, Version, WriteGCode\n"
  6935. "#\n\n"
  6936. ))
  6937. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  6938. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  6939. self.ui.buttonRun.show()
  6940. self.ui.buttonRun.clicked.connect(self.handleRunCode)
  6941. self.handleTextChanged()
  6942. self.ui.code_editor.show()
  6943. def on_fileopenscript(self):
  6944. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  6945. try:
  6946. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  6947. directory=self.get_last_folder(), filter=_filter_)
  6948. except TypeError:
  6949. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  6950. # The Qt methods above will return a QString which can cause problems later.
  6951. # So far json.dump() will fail to serialize it.
  6952. # TODO: Improve the serialization methods and remove this fix.
  6953. filename = str(filename)
  6954. if filename == "":
  6955. self.inform.emit('[WARNING_NOTCL] %s' %
  6956. _("Open TCL script cancelled."))
  6957. else:
  6958. self.on_filenewscript()
  6959. try:
  6960. with open(filename, "r") as opened_script:
  6961. try:
  6962. for line in opened_script:
  6963. proc_line = str(line).strip('\n')
  6964. self.ui.code_editor.append(proc_line)
  6965. except Exception as e:
  6966. log.debug('App.on_fileopenscript() -->%s' % str(e))
  6967. self.inform.emit('[ERROR] %s %s' %
  6968. (_('App.on_fileopenscript() -->'), str(e)))
  6969. return
  6970. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6971. self.handleTextChanged()
  6972. # self.ui.show()
  6973. except Exception as e:
  6974. log.debug("App.on_fileopenscript() -> %s" % str(e))
  6975. def on_filerunscript(self, name=None):
  6976. """
  6977. File menu callback for loading and running a TCL script.
  6978. :return: None
  6979. """
  6980. self.report_usage("on_filerunscript")
  6981. App.log.debug("on_file_runscript()")
  6982. if name:
  6983. filename = name
  6984. else:
  6985. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  6986. try:
  6987. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6988. directory=self.get_last_folder(), filter=_filter_)
  6989. except TypeError:
  6990. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6991. # The Qt methods above will return a QString which can cause problems later.
  6992. # So far json.dump() will fail to serialize it.
  6993. # TODO: Improve the serialization methods and remove this fix.
  6994. filename = str(filename)
  6995. if filename == "":
  6996. self.inform.emit('[WARNING_NOTCL] %s' %
  6997. _("Run TCL script cancelled."))
  6998. else:
  6999. try:
  7000. with open(filename, "r") as tcl_script:
  7001. cmd_line_shellfile_content = tcl_script.read()
  7002. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  7003. except Exception as e:
  7004. log.debug("App.on_filerunscript() -> %s" % str(e))
  7005. sys.exit(2)
  7006. def on_file_saveproject(self):
  7007. """
  7008. Callback for menu item File->Save Project. Saves the project to
  7009. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7010. if set to None. The project is saved by calling ``self.save_project()``.
  7011. :return: None
  7012. """
  7013. self.report_usage("on_file_saveproject")
  7014. if self.project_filename is None:
  7015. self.on_file_saveprojectas()
  7016. else:
  7017. self.worker_task.emit({'fcn': self.save_project,
  7018. 'params': [self.project_filename]})
  7019. if self.defaults["global_open_style"] is False:
  7020. self.file_opened.emit("project", self.project_filename)
  7021. self.file_saved.emit("project", self.project_filename)
  7022. self.set_ui_title(name=self.project_filename)
  7023. self.should_we_save = False
  7024. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7025. """
  7026. Callback for menu item File->Save Project As... Opens a file
  7027. chooser and saves the project to the given file via
  7028. ``self.save_project()``.
  7029. :param make_copy if to be create a copy of the project; boolean
  7030. :param use_thread: if to be run in a separate thread; boolean
  7031. :param quit_action: if to be followed by quiting the application; boolean
  7032. :return: None
  7033. """
  7034. self.report_usage("on_file_saveprojectas")
  7035. self.date = str(datetime.today()).rpartition('.')[0]
  7036. self.date = ''.join(c for c in self.date if c not in ':-')
  7037. self.date = self.date.replace(' ', '_')
  7038. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  7039. try:
  7040. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7041. caption=_("Save Project As ..."),
  7042. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  7043. filter=filter_)
  7044. except TypeError:
  7045. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  7046. filename = str(filename)
  7047. if filename == '':
  7048. self.inform.emit('[WARNING_NOTCL] %s' %
  7049. _("Save Project cancelled."))
  7050. return
  7051. try:
  7052. f = open(filename, 'r')
  7053. f.close()
  7054. except IOError:
  7055. pass
  7056. if use_thread is True:
  7057. self.worker_task.emit({'fcn': self.save_project,
  7058. 'params': [filename, quit_action]})
  7059. else:
  7060. self.save_project(filename, quit_action)
  7061. # self.save_project(filename)
  7062. if self.defaults["global_open_style"] is False:
  7063. self.file_opened.emit("project", filename)
  7064. self.file_saved.emit("project", filename)
  7065. if not make_copy:
  7066. self.project_filename = filename
  7067. self.set_ui_title(name=self.project_filename)
  7068. self.should_we_save = False
  7069. def export_svg(self, obj_name, filename, scale_factor=0.00):
  7070. """
  7071. Exports a Geometry Object to an SVG file.
  7072. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7073. :param filename: Path to the SVG file to save to.
  7074. :param scale_factor: factor by which to change/scale the thickness of the features
  7075. :return:
  7076. """
  7077. self.report_usage("export_svg()")
  7078. if filename is None:
  7079. filename = self.defaults["global_last_save_folder"]
  7080. self.log.debug("export_svg()")
  7081. try:
  7082. obj = self.collection.get_by_name(str(obj_name))
  7083. except:
  7084. # TODO: The return behavior has not been established... should raise exception?
  7085. return "Could not retrieve object: %s" % obj_name
  7086. with self.proc_container.new(_("Exporting SVG")) as proc:
  7087. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7088. # Determine bounding area for svg export
  7089. bounds = obj.bounds()
  7090. size = obj.size()
  7091. # Convert everything to strings for use in the xml doc
  7092. svgwidth = str(size[0])
  7093. svgheight = str(size[1])
  7094. minx = str(bounds[0])
  7095. miny = str(bounds[1] - size[1])
  7096. uom = obj.units.lower()
  7097. # Add a SVG Header and footer to the svg output from shapely
  7098. # The transform flips the Y Axis so that everything renders
  7099. # properly within svg apps such as inkscape
  7100. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7101. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7102. svg_header += 'width="' + svgwidth + uom + '" '
  7103. svg_header += 'height="' + svgheight + uom + '" '
  7104. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7105. svg_header += '<g transform="scale(1,-1)">'
  7106. svg_footer = '</g> </svg>'
  7107. svg_elem = svg_header + exported_svg + svg_footer
  7108. # Parse the xml through a xml parser just to add line feeds
  7109. # and to make it look more pretty for the output
  7110. svgcode = parse_xml_string(svg_elem)
  7111. try:
  7112. with open(filename, 'w') as fp:
  7113. fp.write(svgcode.toprettyxml())
  7114. except PermissionError:
  7115. self.inform.emit('[WARNING] %s' %
  7116. _("Permission denied, saving not possible.\n"
  7117. "Most likely another app is holding the file open and not accessible."))
  7118. return 'fail'
  7119. if self.defaults["global_open_style"] is False:
  7120. self.file_opened.emit("SVG", filename)
  7121. self.file_saved.emit("SVG", filename)
  7122. self.inform.emit('[success] %s: %s' %
  7123. (_("SVG file exported to"), filename))
  7124. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  7125. """
  7126. Exports a Geometry Object to an SVG file in negative.
  7127. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7128. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7129. :param filename: Path to the SVG file to save to.
  7130. :param boundary: thickness of a black border to surround all the features
  7131. :param scale_factor: factor by which to change/scale the thickness of the features
  7132. :param use_thread: if to be run in a separate thread; boolean
  7133. :return:
  7134. """
  7135. self.report_usage("export_negative()")
  7136. if filename is None:
  7137. filename = self.defaults["global_last_save_folder"]
  7138. self.log.debug("export_svg() negative")
  7139. try:
  7140. obj = self.collection.get_by_name(str(obj_name))
  7141. except:
  7142. # TODO: The return behavior has not been established... should raise exception?
  7143. return "Could not retrieve object: %s" % obj_name
  7144. try:
  7145. box = self.collection.get_by_name(str(box_name))
  7146. except:
  7147. # TODO: The return behavior has not been established... should raise exception?
  7148. return "Could not retrieve object: %s" % box_name
  7149. if box is None:
  7150. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7151. (_("No object Box. Using instead"), obj))
  7152. box = obj
  7153. def make_negative_film():
  7154. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7155. self.progress.emit(40)
  7156. # Determine bounding area for svg export
  7157. bounds = box.bounds()
  7158. size = box.size()
  7159. uom = obj.units.lower()
  7160. # Convert everything to strings for use in the xml doc
  7161. svgwidth = str(size[0] + (2 * boundary))
  7162. svgheight = str(size[1] + (2 * boundary))
  7163. minx = str(bounds[0] - boundary)
  7164. miny = str(bounds[1] + boundary + size[1])
  7165. miny_rect = str(bounds[1] - boundary)
  7166. # Add a SVG Header and footer to the svg output from shapely
  7167. # The transform flips the Y Axis so that everything renders
  7168. # properly within svg apps such as inkscape
  7169. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7170. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7171. svg_header += 'width="' + svgwidth + uom + '" '
  7172. svg_header += 'height="' + svgheight + uom + '" '
  7173. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7174. svg_header += '>'
  7175. svg_header += '<g transform="scale(1,-1)">'
  7176. svg_footer = '</g> </svg>'
  7177. self.progress.emit(60)
  7178. # Change the attributes of the exported SVG
  7179. # We don't need stroke-width - wrong, we do when we have lines with certain width
  7180. # We set opacity to maximum
  7181. # We set the color to WHITE
  7182. root = ET.fromstring(exported_svg)
  7183. for child in root:
  7184. child.set('fill', '#FFFFFF')
  7185. child.set('opacity', '1.0')
  7186. child.set('stroke', '#FFFFFF')
  7187. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  7188. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  7189. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  7190. first_svg_elem_tag = 'rect'
  7191. first_svg_elem_attribs = {
  7192. 'x': minx,
  7193. 'y': miny_rect,
  7194. 'width': svgwidth,
  7195. 'height': svgheight,
  7196. 'id': 'neg_rect',
  7197. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  7198. }
  7199. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  7200. exported_svg = ET.tostring(root)
  7201. svg_elem = svg_header + str(exported_svg) + svg_footer
  7202. self.progress.emit(80)
  7203. # Parse the xml through a xml parser just to add line feeds
  7204. # and to make it look more pretty for the output
  7205. doc = parse_xml_string(svg_elem)
  7206. try:
  7207. with open(filename, 'w') as fp:
  7208. fp.write(doc.toprettyxml())
  7209. except PermissionError:
  7210. self.inform.emit('[WARNING] %s' %
  7211. _("Permission denied, saving not possible.\n"
  7212. "Most likely another app is holding the file open and not accessible."))
  7213. return 'fail'
  7214. self.progress.emit(100)
  7215. if self.defaults["global_open_style"] is False:
  7216. self.file_opened.emit("SVG", filename)
  7217. self.file_saved.emit("SVG", filename)
  7218. self.inform.emit('[success] %s: %s' %
  7219. (_("SVG file exported to"), filename))
  7220. if use_thread is True:
  7221. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7222. def job_thread_film(app_obj):
  7223. try:
  7224. make_negative_film()
  7225. except Exception as e:
  7226. proc.done()
  7227. return
  7228. proc.done()
  7229. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7230. else:
  7231. make_negative_film()
  7232. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  7233. """
  7234. Exports a Geometry Object to an SVG file in positive black.
  7235. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7236. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7237. :param filename: Path to the SVG file to save to.
  7238. :param scale_factor: factor by which to change/scale the thickness of the features
  7239. :param use_thread: if to be run in a separate thread; boolean
  7240. :return:
  7241. """
  7242. self.report_usage("export_svg_black()")
  7243. if filename is None:
  7244. filename = self.defaults["global_last_save_folder"]
  7245. self.log.debug("export_svg() black")
  7246. try:
  7247. obj = self.collection.get_by_name(str(obj_name))
  7248. except:
  7249. # TODO: The return behavior has not been established... should raise exception?
  7250. return "Could not retrieve object: %s" % obj_name
  7251. try:
  7252. box = self.collection.get_by_name(str(box_name))
  7253. except:
  7254. # TODO: The return behavior has not been established... should raise exception?
  7255. return "Could not retrieve object: %s" % box_name
  7256. if box is None:
  7257. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7258. (_("No object Box. Using instead"), obj))
  7259. box = obj
  7260. def make_black_film():
  7261. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7262. self.progress.emit(40)
  7263. # Change the attributes of the exported SVG
  7264. # We don't need stroke-width
  7265. # We set opacity to maximum
  7266. # We set the colour to WHITE
  7267. root = ET.fromstring(exported_svg)
  7268. for child in root:
  7269. child.set('fill', '#000000')
  7270. child.set('opacity', '1.0')
  7271. child.set('stroke', '#000000')
  7272. exported_svg = ET.tostring(root)
  7273. # Determine bounding area for svg export
  7274. bounds = box.bounds()
  7275. size = box.size()
  7276. # This contain the measure units
  7277. uom = obj.units.lower()
  7278. # Define a boundary around SVG of about 1.0mm (~39mils)
  7279. if uom in "mm":
  7280. boundary = 1.0
  7281. else:
  7282. boundary = 0.0393701
  7283. self.progress.emit(80)
  7284. # Convert everything to strings for use in the xml doc
  7285. svgwidth = str(size[0] + (2 * boundary))
  7286. svgheight = str(size[1] + (2 * boundary))
  7287. minx = str(bounds[0] - boundary)
  7288. miny = str(bounds[1] + boundary + size[1])
  7289. self.log.debug(minx)
  7290. self.log.debug(miny)
  7291. # Add a SVG Header and footer to the svg output from shapely
  7292. # The transform flips the Y Axis so that everything renders
  7293. # properly within svg apps such as inkscape
  7294. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7295. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7296. svg_header += 'width="' + svgwidth + uom + '" '
  7297. svg_header += 'height="' + svgheight + uom + '" '
  7298. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7299. svg_header += '>'
  7300. svg_header += '<g transform="scale(1,-1)">'
  7301. svg_footer = '</g> </svg>'
  7302. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  7303. self.progress.emit(90)
  7304. # Parse the xml through a xml parser just to add line feeds
  7305. # and to make it look more pretty for the output
  7306. doc = parse_xml_string(svg_elem)
  7307. try:
  7308. with open(filename, 'w') as fp:
  7309. fp.write(doc.toprettyxml())
  7310. except PermissionError:
  7311. self.inform.emit('[WARNING] %s' %
  7312. _("Permission denied, saving not possible.\n"
  7313. "Most likely another app is holding the file open and not accessible."))
  7314. return 'fail'
  7315. self.progress.emit(100)
  7316. if self.defaults["global_open_style"] is False:
  7317. self.file_opened.emit("SVG", filename)
  7318. self.file_saved.emit("SVG", filename)
  7319. self.inform.emit('[success] %s: %s' %
  7320. (_("SVG file exported to"), filename))
  7321. if use_thread is True:
  7322. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7323. def job_thread_film(app_obj):
  7324. try:
  7325. make_black_film()
  7326. except Exception as e:
  7327. proc.done()
  7328. return
  7329. proc.done()
  7330. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7331. else:
  7332. make_black_film()
  7333. def save_source_file(self, obj_name, filename, use_thread=True):
  7334. """
  7335. Exports a FlatCAM Object to an Gerber/Excellon file.
  7336. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7337. :param filename: Path to the Gerber file to save to.
  7338. :param use_thread: if to be run in a separate thread
  7339. :return:
  7340. """
  7341. self.report_usage("save source file()")
  7342. if filename is None:
  7343. filename = self.defaults["global_last_save_folder"]
  7344. self.log.debug("save source file()")
  7345. obj = self.collection.get_by_name(obj_name)
  7346. file_string = StringIO(obj.source_file)
  7347. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7348. try:
  7349. with open(filename, 'w') as file:
  7350. file.writelines('G04*\n')
  7351. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7352. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7353. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7354. file.writelines('G04 Created on : %s*\n' % time_string)
  7355. for line in file_string:
  7356. file.writelines(line)
  7357. except PermissionError:
  7358. self.inform.emit('[WARNING] %s' %
  7359. _("Permission denied, saving not possible.\n"
  7360. "Most likely another app is holding the file open and not accessible."))
  7361. return 'fail'
  7362. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7363. """
  7364. Exports a Excellon Object to an Excellon file.
  7365. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7366. :param filename: Path to the Excellon file to save to.
  7367. :param use_thread: if to be run in a separate thread
  7368. :return:
  7369. """
  7370. self.report_usage("export_excellon()")
  7371. if filename is None:
  7372. filename = self.defaults["global_last_save_folder"]
  7373. self.log.debug("export_excellon()")
  7374. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7375. self.defaults["excellon_exp_decimals"]
  7376. )
  7377. units = ''
  7378. if local_use is None:
  7379. try:
  7380. obj = self.collection.get_by_name(str(obj_name))
  7381. except:
  7382. # TODO: The return behavior has not been established... should raise exception?
  7383. return "Could not retrieve object: %s" % obj_name
  7384. else:
  7385. obj = local_use
  7386. # updated units
  7387. eunits = self.defaults["excellon_exp_units"]
  7388. ewhole = self.defaults["excellon_exp_integer"]
  7389. efract = self.defaults["excellon_exp_decimals"]
  7390. ezeros = self.defaults["excellon_exp_zeros"]
  7391. eformat = self.defaults["excellon_exp_format"]
  7392. slot_type = self.defaults["excellon_exp_slot_type"]
  7393. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7394. if fc_units == 'MM':
  7395. factor = 1 if eunits == 'METRIC' else 0.03937
  7396. else:
  7397. factor = 25.4 if eunits == 'METRIC' else 1
  7398. def make_excellon():
  7399. try:
  7400. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7401. header = 'M48\n'
  7402. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7403. (str(self.version), str(self.version_date))
  7404. header += ';Filename: %s' % str(obj_name) + '\n'
  7405. header += ';Created on : %s' % time_str + '\n'
  7406. if eformat == 'dec':
  7407. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7408. header += eunits + '\n'
  7409. for tool in obj.tools:
  7410. if eunits == 'METRIC':
  7411. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7412. tool=str(tool),
  7413. dec=2)
  7414. else:
  7415. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7416. tool=str(tool),
  7417. dec=4)
  7418. else:
  7419. if ezeros == 'LZ':
  7420. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7421. form='ndec', e_zeros='LZ', factor=factor,
  7422. slot_type=slot_type)
  7423. header += '%s,%s\n' % (eunits, 'LZ')
  7424. header += format_exc
  7425. for tool in obj.tools:
  7426. if eunits == 'METRIC':
  7427. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7428. tool=str(tool),
  7429. dec=2)
  7430. else:
  7431. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7432. tool=str(tool),
  7433. dec=4)
  7434. else:
  7435. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7436. form='ndec', e_zeros='TZ', factor=factor,
  7437. slot_type=slot_type)
  7438. header += '%s,%s\n' % (eunits, 'TZ')
  7439. header += format_exc
  7440. for tool in obj.tools:
  7441. if eunits == 'METRIC':
  7442. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7443. tool=str(tool),
  7444. dec=2)
  7445. else:
  7446. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7447. tool=str(tool),
  7448. dec=4)
  7449. header += '%\n'
  7450. footer = 'M30\n'
  7451. exported_excellon = header
  7452. exported_excellon += excellon_code
  7453. exported_excellon += footer
  7454. if local_use is None:
  7455. try:
  7456. with open(filename, 'w') as fp:
  7457. fp.write(exported_excellon)
  7458. except PermissionError:
  7459. self.inform.emit('[WARNING] %s' %
  7460. _("Permission denied, saving not possible.\n"
  7461. "Most likely another app is holding the file open and not accessible."))
  7462. return 'fail'
  7463. if self.defaults["global_open_style"] is False:
  7464. self.file_opened.emit("Excellon", filename)
  7465. self.file_saved.emit("Excellon", filename)
  7466. self.inform.emit('[success] %s: %s' %
  7467. (_("Excellon file exported to"), filename))
  7468. else:
  7469. return exported_excellon
  7470. except Exception as e:
  7471. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7472. return 'fail'
  7473. if use_thread is True:
  7474. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7475. def job_thread_exc(app_obj):
  7476. ret = make_excellon()
  7477. if ret == 'fail':
  7478. self.inform.emit('[ERROR_NOTCL] %s' %
  7479. _('Could not export Excellon file.'))
  7480. return
  7481. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7482. else:
  7483. ret = make_excellon()
  7484. if ret == 'fail':
  7485. self.inform.emit('[ERROR_NOTCL] %s' %
  7486. _('Could not export Excellon file.'))
  7487. return 'fail'
  7488. if local_use is not None:
  7489. return ret
  7490. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7491. """
  7492. Exports a Gerber Object to an Gerber file.
  7493. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7494. :param filename: Path to the Gerber file to save to.
  7495. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7496. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7497. :param use_thread: if to be run in a separate thread
  7498. :return:
  7499. """
  7500. self.report_usage("export_gerber()")
  7501. if filename is None:
  7502. filename = self.defaults["global_last_save_folder"]
  7503. self.log.debug("export_gerber()")
  7504. if local_use is None:
  7505. try:
  7506. obj = self.collection.get_by_name(str(obj_name))
  7507. except:
  7508. # TODO: The return behavior has not been established... should raise exception?
  7509. return "Could not retrieve object: %s" % obj_name
  7510. else:
  7511. obj = local_use
  7512. # updated units
  7513. gunits = self.defaults["gerber_exp_units"]
  7514. gwhole = self.defaults["gerber_exp_integer"]
  7515. gfract = self.defaults["gerber_exp_decimals"]
  7516. gzeros = self.defaults["gerber_exp_zeros"]
  7517. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7518. if fc_units == 'MM':
  7519. factor = 1 if gunits == 'MM' else 0.03937
  7520. else:
  7521. factor = 25.4 if gunits == 'MM' else 1
  7522. def make_gerber():
  7523. try:
  7524. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7525. header = 'G04*\n'
  7526. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7527. (str(self.version), str(self.version_date))
  7528. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7529. header += 'G04 Created on : %s*' % time_str + '\n'
  7530. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7531. header += "%MO{units}*%\n".format(units=gunits)
  7532. for apid in obj.apertures:
  7533. if obj.apertures[apid]['type'] == 'C':
  7534. header += "%ADD{apid}{type},{size}*%\n".format(
  7535. apid=str(apid),
  7536. type='C',
  7537. size=(factor * obj.apertures[apid]['size'])
  7538. )
  7539. elif obj.apertures[apid]['type'] == 'R':
  7540. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7541. apid=str(apid),
  7542. type='R',
  7543. width=(factor * obj.apertures[apid]['width']),
  7544. height=(factor * obj.apertures[apid]['height'])
  7545. )
  7546. elif obj.apertures[apid]['type'] == 'O':
  7547. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7548. apid=str(apid),
  7549. type='O',
  7550. width=(factor * obj.apertures[apid]['width']),
  7551. height=(factor * obj.apertures[apid]['height'])
  7552. )
  7553. header += '\n'
  7554. # obsolete units but some software may need it
  7555. if gunits == 'IN':
  7556. header += 'G70*\n'
  7557. else:
  7558. header += 'G71*\n'
  7559. # Absolute Mode
  7560. header += 'G90*\n'
  7561. header += 'G01*\n'
  7562. # positive polarity
  7563. header += '%LPD*%\n'
  7564. footer = 'M02*\n'
  7565. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7566. exported_gerber = header
  7567. exported_gerber += gerber_code
  7568. exported_gerber += footer
  7569. if local_use is None:
  7570. try:
  7571. with open(filename, 'w') as fp:
  7572. fp.write(exported_gerber)
  7573. except PermissionError:
  7574. self.inform.emit('[WARNING] %s' %
  7575. _("Permission denied, saving not possible.\n"
  7576. "Most likely another app is holding the file open and not accessible."))
  7577. return 'fail'
  7578. if self.defaults["global_open_style"] is False:
  7579. self.file_opened.emit("Gerber", filename)
  7580. self.file_saved.emit("Gerber", filename)
  7581. self.inform.emit('[success] %s: %s' %
  7582. (_("Gerber file exported to"), filename))
  7583. else:
  7584. return exported_gerber
  7585. except Exception as e:
  7586. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7587. return 'fail'
  7588. if use_thread is True:
  7589. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7590. def job_thread_grb(app_obj):
  7591. ret = make_gerber()
  7592. if ret == 'fail':
  7593. self.inform.emit('[ERROR_NOTCL] %s' %
  7594. _('Could not export Gerber file.'))
  7595. return
  7596. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7597. else:
  7598. ret = make_gerber()
  7599. if ret == 'fail':
  7600. self.inform.emit('[ERROR_NOTCL] %s' %
  7601. _('Could not export Gerber file.'))
  7602. return 'fail'
  7603. if local_use is not None:
  7604. return ret
  7605. def export_dxf(self, obj_name, filename, use_thread=True):
  7606. """
  7607. Exports a Geometry Object to an DXF file.
  7608. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7609. :param filename: Path to the DXF file to save to.
  7610. :param use_thread: if to be run in a separate thread
  7611. :return:
  7612. """
  7613. self.report_usage("export_dxf()")
  7614. if filename is None:
  7615. filename = self.defaults["global_last_save_folder"]
  7616. self.log.debug("export_dxf()")
  7617. format_exc = ''
  7618. units = ''
  7619. try:
  7620. obj = self.collection.get_by_name(str(obj_name))
  7621. except:
  7622. # TODO: The return behavior has not been established... should raise exception?
  7623. return "Could not retrieve object: %s" % obj_name
  7624. # updated units
  7625. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7626. if units == 'IN' or units == 'INCH':
  7627. units = 'INCH'
  7628. elif units == 'MM' or units == 'METIRC':
  7629. units ='METRIC'
  7630. def make_dxf():
  7631. try:
  7632. dxf_code = obj.export_dxf()
  7633. dxf_code.saveas(filename)
  7634. if self.defaults["global_open_style"] is False:
  7635. self.file_opened.emit("DXF", filename)
  7636. self.file_saved.emit("DXF", filename)
  7637. self.inform.emit('[success] %s: %s' %
  7638. (_("DXF file exported to"), filename))
  7639. except:
  7640. return 'fail'
  7641. if use_thread is True:
  7642. with self.proc_container.new(_("Exporting DXF")) as proc:
  7643. def job_thread_exc(app_obj):
  7644. ret = make_dxf()
  7645. if ret == 'fail':
  7646. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  7647. _('Could not export DXF file.'))
  7648. return
  7649. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7650. else:
  7651. ret = make_dxf()
  7652. if ret == 'fail':
  7653. self.inform.emit('[WARNING_NOTCL] %s' %
  7654. _('Could not export DXF file.'))
  7655. return
  7656. def import_svg(self, filename, geo_type='geometry', outname=None):
  7657. """
  7658. Adds a new Geometry Object to the projects and populates
  7659. it with shapes extracted from the SVG file.
  7660. :param filename: Path to the SVG file.
  7661. :param outname:
  7662. :return:
  7663. """
  7664. self.report_usage("import_svg()")
  7665. obj_type = ""
  7666. if geo_type is None or geo_type == "geometry":
  7667. obj_type = "geometry"
  7668. elif geo_type == "gerber":
  7669. obj_type = geo_type
  7670. else:
  7671. self.inform.emit('[ERROR_NOTCL] %s' %
  7672. _("Not supported type is picked as parameter. "
  7673. "Only Geometry and Gerber are supported"))
  7674. return
  7675. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7676. def obj_init(geo_obj, app_obj):
  7677. geo_obj.import_svg(filename, obj_type, units=units)
  7678. geo_obj.multigeo = False
  7679. with self.proc_container.new(_("Importing SVG")) as proc:
  7680. # Object name
  7681. name = outname or filename.split('/')[-1].split('\\')[-1]
  7682. self.new_object(obj_type, name, obj_init, autoselected=False)
  7683. self.progress.emit(20)
  7684. # Register recent file
  7685. self.file_opened.emit("svg", filename)
  7686. # GUI feedback
  7687. self.inform.emit('[success] %s: %s' %
  7688. (_("Opened"), filename))
  7689. self.progress.emit(100)
  7690. def import_dxf(self, filename, geo_type='geometry', outname=None):
  7691. """
  7692. Adds a new Geometry Object to the projects and populates
  7693. it with shapes extracted from the DXF file.
  7694. :param filename: Path to the DXF file.
  7695. :param outname:
  7696. :type putname: str
  7697. :return:
  7698. """
  7699. self.report_usage("import_dxf()")
  7700. obj_type = ""
  7701. if geo_type is None or geo_type == "geometry":
  7702. obj_type = "geometry"
  7703. elif geo_type == "gerber":
  7704. obj_type = geo_type
  7705. else:
  7706. self.inform.emit('[ERROR_NOTCL] %s' %
  7707. _("Not supported type is picked as parameter. "
  7708. "Only Geometry and Gerber are supported"))
  7709. return
  7710. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7711. def obj_init(geo_obj, app_obj):
  7712. geo_obj.import_dxf(filename, obj_type, units=units)
  7713. geo_obj.multigeo = False
  7714. with self.proc_container.new(_("Importing DXF")) as proc:
  7715. # Object name
  7716. name = outname or filename.split('/')[-1].split('\\')[-1]
  7717. self.new_object(obj_type, name, obj_init, autoselected=False)
  7718. self.progress.emit(20)
  7719. # Register recent file
  7720. self.file_opened.emit("dxf", filename)
  7721. # GUI feedback
  7722. self.inform.emit('[success] %s: %s' %
  7723. (_("Opened"), filename))
  7724. self.progress.emit(100)
  7725. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  7726. """
  7727. Adds a new Geometry Object to the projects and populates
  7728. it with shapes extracted from the SVG file.
  7729. :param filename: Path to the SVG file.
  7730. :param o_type: type of FlatCAM objeect
  7731. :param dpi: dot per inch
  7732. :param mode: black or color
  7733. :param mask: dictate the level of detail
  7734. :param outname: name for the resulting file
  7735. :return:
  7736. """
  7737. self.report_usage("import_image()")
  7738. if o_type is None or o_type == "geometry":
  7739. obj_type = "geometry"
  7740. elif o_type == "gerber":
  7741. obj_type = o_type
  7742. else:
  7743. self.inform.emit('[ERROR_NOTCL] %s' %
  7744. _("Not supported type is picked as parameter. "
  7745. "Only Geometry and Gerber are supported"))
  7746. return
  7747. def obj_init(geo_obj, app_obj):
  7748. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  7749. geo_obj.multigeo = False
  7750. with self.proc_container.new(_("Importing Image")) as proc:
  7751. # Object name
  7752. name = outname or filename.split('/')[-1].split('\\')[-1]
  7753. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  7754. self.new_object(obj_type, name, obj_init)
  7755. self.progress.emit(20)
  7756. # Register recent file
  7757. self.file_opened.emit("image", filename)
  7758. # GUI feedback
  7759. self.inform.emit('[success] %s: %s' %
  7760. (_("Opened"), filename))
  7761. self.progress.emit(100)
  7762. def open_gerber(self, filename, outname=None):
  7763. """
  7764. Opens a Gerber file, parses it and creates a new object for
  7765. it in the program. Thread-safe.
  7766. :param outname: Name of the resulting object. None causes the
  7767. name to be that of the file.
  7768. :param filename: Gerber file filename
  7769. :type filename: str
  7770. :param follow: If true, the parser will not create polygons, just lines
  7771. following the gerber path.
  7772. :type follow: bool
  7773. :return: None
  7774. """
  7775. # How the object should be initialized
  7776. def obj_init(gerber_obj, app_obj):
  7777. assert isinstance(gerber_obj, FlatCAMGerber), \
  7778. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  7779. # Opening the file happens here
  7780. self.progress.emit(30)
  7781. try:
  7782. gerber_obj.parse_file(filename)
  7783. except IOError:
  7784. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7785. (_("Failed to open file"), filename))
  7786. app_obj.progress.emit(0)
  7787. return "fail"
  7788. except ParseError as err:
  7789. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  7790. (_("Failed to parse file"), filename, str(err)))
  7791. app_obj.progress.emit(0)
  7792. self.log.error(str(err))
  7793. return "fail"
  7794. except Exception as e:
  7795. log.debug("App.open_gerber() --> %s" % str(e))
  7796. msg = '[ERROR] %s' % \
  7797. _("An internal error has occurred. See shell.\n")
  7798. msg += traceback.format_exc()
  7799. app_obj.inform.emit(msg)
  7800. return "fail"
  7801. if gerber_obj.is_empty():
  7802. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  7803. # self.collection.set_active(gerber_obj.options["name"])
  7804. # self.collection.delete_active()
  7805. self.inform.emit('[ERROR_NOTCL] %s' %
  7806. _("Object is not Gerber file or empty. Aborting object creation."))
  7807. return "fail"
  7808. # Further parsing
  7809. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  7810. App.log.debug("open_gerber()")
  7811. with self.proc_container.new(_("Opening Gerber")) as proc:
  7812. self.progress.emit(10)
  7813. # Object name
  7814. name = outname or filename.split('/')[-1].split('\\')[-1]
  7815. # # ## Object creation # ##
  7816. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  7817. if ret == 'fail':
  7818. self.inform.emit('[ERROR_NOTCL]%s' %
  7819. _(' Open Gerber failed. Probable not a Gerber file.'))
  7820. return
  7821. # Register recent file
  7822. self.file_opened.emit("gerber", filename)
  7823. self.progress.emit(100)
  7824. # GUI feedback
  7825. self.inform.emit('[success] %s: %s' %
  7826. (_("Opened"), filename))
  7827. def open_excellon(self, filename, outname=None):
  7828. """
  7829. Opens an Excellon file, parses it and creates a new object for
  7830. it in the program. Thread-safe.
  7831. :param outname: Name of the resulting object. None causes the
  7832. name to be that of the file.
  7833. :param filename: Excellon file filename
  7834. :type filename: str
  7835. :return: None
  7836. """
  7837. App.log.debug("open_excellon()")
  7838. # How the object should be initialized
  7839. def obj_init(excellon_obj, app_obj):
  7840. # self.progress.emit(20)
  7841. try:
  7842. ret = excellon_obj.parse_file(filename=filename)
  7843. if ret == "fail":
  7844. log.debug("Excellon parsing failed.")
  7845. self.inform.emit('[ERROR_NOTCL] %s' %
  7846. _("This is not Excellon file."))
  7847. return "fail"
  7848. except IOError:
  7849. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7850. (_("Cannot open file"), filename))
  7851. log.debug("Could not open Excellon object.")
  7852. self.progress.emit(0) # TODO: self and app_bjj mixed
  7853. return "fail"
  7854. except:
  7855. msg = '[ERROR_NOTCL] %s' % \
  7856. _("An internal error has occurred. See shell.\n")
  7857. msg += traceback.format_exc()
  7858. app_obj.inform.emit(msg)
  7859. return "fail"
  7860. ret = excellon_obj.create_geometry()
  7861. if ret == 'fail':
  7862. log.debug("Could not create geometry for Excellon object.")
  7863. return "fail"
  7864. for tool in excellon_obj.tools:
  7865. if excellon_obj.tools[tool]['solid_geometry']:
  7866. return
  7867. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7868. (_("No geometry found in file"), filename))
  7869. return "fail"
  7870. with self.proc_container.new(_("Opening Excellon.")):
  7871. # Object name
  7872. name = outname or filename.split('/')[-1].split('\\')[-1]
  7873. ret_val = self.new_object("excellon", name, obj_init, autoselected=False)
  7874. if ret_val == 'fail':
  7875. self.inform.emit('[ERROR_NOTCL] %s' %
  7876. _('Open Excellon file failed. Probable not an Excellon file.'))
  7877. return
  7878. # Register recent file
  7879. self.file_opened.emit("excellon", filename)
  7880. # GUI feedback
  7881. self.inform.emit('[success] %s: %s' %
  7882. (_("Opened"), filename))
  7883. def open_gcode(self, filename, outname=None):
  7884. """
  7885. Opens a G-gcode file, parses it and creates a new object for
  7886. it in the program. Thread-safe.
  7887. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7888. :param filename: G-code file filename
  7889. :type filename: str
  7890. :return: None
  7891. """
  7892. App.log.debug("open_gcode()")
  7893. # How the object should be initialized
  7894. def obj_init(job_obj, app_obj_):
  7895. """
  7896. :param job_obj: the resulting object
  7897. :type app_obj_: App
  7898. """
  7899. assert isinstance(app_obj_, App), \
  7900. "Initializer expected App, got %s" % type(app_obj_)
  7901. self.progress.emit(10)
  7902. try:
  7903. f = open(filename)
  7904. gcode = f.read()
  7905. f.close()
  7906. except IOError:
  7907. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  7908. (_("Failed to open"), filename))
  7909. self.progress.emit(0)
  7910. return "fail"
  7911. job_obj.gcode = gcode
  7912. self.progress.emit(20)
  7913. ret = job_obj.gcode_parse()
  7914. if ret == "fail":
  7915. self.inform.emit('[ERROR_NOTCL] %s' %
  7916. _("This is not GCODE"))
  7917. return "fail"
  7918. self.progress.emit(60)
  7919. job_obj.create_geometry()
  7920. with self.proc_container.new(_("Opening G-Code.")):
  7921. # Object name
  7922. name = outname or filename.split('/')[-1].split('\\')[-1]
  7923. # New object creation and file processing
  7924. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  7925. if ret == 'fail':
  7926. self.inform.emit('[ERROR_NOTCL] %s' %
  7927. _("Failed to create CNCJob Object. Probable not a GCode file.\n "
  7928. "Attempting to create a FlatCAM CNCJob Object from "
  7929. "G-Code file failed during processing"))
  7930. return "fail"
  7931. # Register recent file
  7932. self.file_opened.emit("cncjob", filename)
  7933. # GUI feedback
  7934. self.inform.emit('[success] %s: %s' %
  7935. (_("Opened"), filename))
  7936. self.progress.emit(100)
  7937. def open_config_file(self, filename, run_from_arg=None):
  7938. """
  7939. Loads a config file from the specified file.
  7940. :param filename: Name of the file from which to load.
  7941. :type filename: str
  7942. :return: None
  7943. """
  7944. App.log.debug("Opening config file: " + filename)
  7945. # add the tab if it was closed
  7946. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  7947. # first clear previous text in text editor (if any)
  7948. self.ui.code_editor.clear()
  7949. # Switch plot_area to CNCJob tab
  7950. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  7951. try:
  7952. if filename:
  7953. f = QtCore.QFile(filename)
  7954. if f.open(QtCore.QIODevice.ReadOnly):
  7955. stream = QtCore.QTextStream(f)
  7956. gcode_edited = stream.readAll()
  7957. self.ui.code_editor.setPlainText(gcode_edited)
  7958. f.close()
  7959. except IOError:
  7960. App.log.error("Failed to open config file: %s" % filename)
  7961. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7962. (_("Failed to open config file"), filename))
  7963. return
  7964. def open_project(self, filename, run_from_arg=None):
  7965. """
  7966. Loads a project from the specified file.
  7967. 1) Loads and parses file
  7968. 2) Registers the file as recently opened.
  7969. 3) Calls on_file_new()
  7970. 4) Updates options
  7971. 5) Calls new_object() with the object's from_dict() as init method.
  7972. 6) Calls plot_all()
  7973. :param filename: Name of the file from which to load.
  7974. :type filename: str
  7975. :param run_from_arg: True if run for arguments
  7976. :return: None
  7977. """
  7978. App.log.debug("Opening project: " + filename)
  7979. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7980. # Open and parse an uncompressed Project file
  7981. try:
  7982. f = open(filename, 'r')
  7983. except IOError:
  7984. App.log.error("Failed to open project file: %s" % filename)
  7985. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7986. (_("Failed to open project file"), filename))
  7987. return
  7988. try:
  7989. d = json.load(f, object_hook=dict2obj)
  7990. except Exception as e:
  7991. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7992. (filename, str(e)))
  7993. f.close()
  7994. # Open and parse a compressed Project file
  7995. try:
  7996. with lzma.open(filename) as f:
  7997. file_content = f.read().decode('utf-8')
  7998. d = json.loads(file_content, object_hook=dict2obj)
  7999. except Exception as e:
  8000. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8001. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8002. (_("Failed to open project file"), filename))
  8003. return
  8004. # Clear the current project
  8005. # # NOT THREAD SAFE # ##
  8006. if run_from_arg is True:
  8007. pass
  8008. else:
  8009. self.on_file_new()
  8010. # Project options
  8011. self.options.update(d['options'])
  8012. self.project_filename = filename
  8013. self.set_screen_units(self.options["units"])
  8014. # Re create objects
  8015. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8016. for obj in d['objs']:
  8017. def obj_init(obj_inst, app_inst):
  8018. obj_inst.from_dict(obj)
  8019. App.log.debug("Recreating from opened project an %s object: %s" %
  8020. (obj['kind'].capitalize(), obj['options']['name']))
  8021. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8022. obj['kind'].upper(),
  8023. obj['options']['name']
  8024. )
  8025. )
  8026. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  8027. # self.plot_all()
  8028. self.inform.emit('[success] %s: %s' %
  8029. (_("Project loaded from"), filename))
  8030. self.should_we_save = False
  8031. self.file_opened.emit("project", filename)
  8032. self.set_ui_title(name=self.project_filename)
  8033. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8034. def propagate_defaults(self, silent=False):
  8035. """
  8036. This method is used to set default values in classes. It's
  8037. an alternative to project options but allows the use
  8038. of values invisible to the user.
  8039. :return: None
  8040. """
  8041. if silent is False:
  8042. self.log.debug("propagate_defaults()")
  8043. # Which objects to update the given parameters.
  8044. routes = {
  8045. "global_zdownrate": CNCjob,
  8046. "excellon_zeros": Excellon,
  8047. "excellon_format_upper_in": Excellon,
  8048. "excellon_format_lower_in": Excellon,
  8049. "excellon_format_upper_mm": Excellon,
  8050. "excellon_format_lower_mm": Excellon,
  8051. "excellon_units": Excellon,
  8052. "gerber_use_buffer_for_union": Gerber,
  8053. "geometry_multidepth": Geometry
  8054. }
  8055. for param in routes:
  8056. if param in routes[param].defaults:
  8057. try:
  8058. routes[param].defaults[param] = self.defaults[param]
  8059. if silent is False:
  8060. self.log.debug(" " + param + " OK")
  8061. except KeyError:
  8062. if silent is False:
  8063. self.log.debug(" ERROR: " + param + " not in defaults.")
  8064. else:
  8065. # Try extracting the name:
  8066. # classname_param here is param in the object
  8067. if param.find(routes[param].__name__.lower() + "_") == 0:
  8068. p = param[len(routes[param].__name__) + 1:]
  8069. if p in routes[param].defaults:
  8070. routes[param].defaults[p] = self.defaults[param]
  8071. if silent is False:
  8072. self.log.debug(" " + param + " OK!")
  8073. def restore_main_win_geom(self):
  8074. try:
  8075. self.ui.setGeometry(self.defaults["global_def_win_x"],
  8076. self.defaults["global_def_win_y"],
  8077. self.defaults["global_def_win_w"],
  8078. self.defaults["global_def_win_h"])
  8079. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  8080. except KeyError as e:
  8081. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  8082. def plot_all(self, zoom=True):
  8083. """
  8084. Re-generates all plots from all objects.
  8085. :return: None
  8086. """
  8087. self.log.debug("Plot_all()")
  8088. for obj in self.collection.get_list():
  8089. def worker_task(obj):
  8090. with self.proc_container.new("Plotting"):
  8091. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8092. if zoom:
  8093. self.object_plotted.emit(obj)
  8094. # Send to worker
  8095. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  8096. def register_folder(self, filename):
  8097. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8098. def register_save_folder(self, filename):
  8099. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8100. def set_progress_bar(self, percentage, text=""):
  8101. self.ui.progress_bar.setValue(int(percentage))
  8102. def setup_shell(self):
  8103. """
  8104. Creates shell functions. Runs once at startup.
  8105. :return: None
  8106. """
  8107. self.log.debug("setup_shell()")
  8108. def shelp(p=None):
  8109. if not p:
  8110. return _("Available commands:\n") + \
  8111. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  8112. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  8113. if p not in commands:
  8114. return "Unknown command: %s" % p
  8115. return commands[p]["help"]
  8116. # --- Migrated to new architecture ---
  8117. # def options(name):
  8118. # ops = self.collection.get_by_name(str(name)).options
  8119. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  8120. def h(*args):
  8121. """
  8122. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  8123. and standalone parameters into list.
  8124. """
  8125. kwa = {}
  8126. a = []
  8127. n = len(args)
  8128. name = None
  8129. for i in range(n):
  8130. match = re.search(r'^-([a-zA-Z].*)', args[i])
  8131. if match:
  8132. assert name is None
  8133. name = match.group(1)
  8134. continue
  8135. if name is None:
  8136. a.append(args[i])
  8137. else:
  8138. kwa[name] = args[i]
  8139. name = None
  8140. return a, kwa
  8141. @contextmanager
  8142. def wait_signal(signal, timeout=10000):
  8143. """
  8144. Block loop until signal emitted, timeout (ms) elapses
  8145. or unhandled exception happens in a thread.
  8146. :param timeout: time after which the loop is exited
  8147. :param signal: Signal to wait for.
  8148. """
  8149. loop = QtCore.QEventLoop()
  8150. # Normal termination
  8151. signal.connect(loop.quit)
  8152. # Termination by exception in thread
  8153. self.thread_exception.connect(loop.quit)
  8154. status = {'timed_out': False}
  8155. def report_quit():
  8156. status['timed_out'] = True
  8157. loop.quit()
  8158. yield
  8159. # Temporarily change how exceptions are managed.
  8160. oeh = sys.excepthook
  8161. ex = []
  8162. def except_hook(type_, value, traceback_):
  8163. ex.append(value)
  8164. oeh(type_, value, traceback_)
  8165. sys.excepthook = except_hook
  8166. # Terminate on timeout
  8167. if timeout is not None:
  8168. QtCore.QTimer.singleShot(timeout, report_quit)
  8169. # # ## Block ## ##
  8170. loop.exec_()
  8171. # Restore exception management
  8172. sys.excepthook = oeh
  8173. if ex:
  8174. self.raiseTclError(str(ex[0]))
  8175. if status['timed_out']:
  8176. raise Exception('Timed out!')
  8177. def make_docs():
  8178. output = ''
  8179. import collections
  8180. od = collections.OrderedDict(sorted(commands.items()))
  8181. for cmd_, val in od.items():
  8182. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  8183. t = val['help']
  8184. usage_i = t.find('>')
  8185. if usage_i < 0:
  8186. expl = t
  8187. output += expl + '\n\n'
  8188. continue
  8189. expl = t[:usage_i - 1]
  8190. output += expl + '\n\n'
  8191. end_usage_i = t[usage_i:].find('\n')
  8192. if end_usage_i < 0:
  8193. end_usage_i = len(t[usage_i:])
  8194. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  8195. else:
  8196. extras = t[usage_i+end_usage_i+1:]
  8197. parts = [s.strip() for s in extras.split('\n')]
  8198. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  8199. for p in parts:
  8200. output += ' ' + p + '\n\n'
  8201. return output
  8202. '''
  8203. Howto implement TCL shell commands:
  8204. All parameters passed to command should be possible to set as None and test it afterwards.
  8205. This is because we need to see error caused in tcl,
  8206. if None value as default parameter is not allowed TCL will return empty error.
  8207. Use:
  8208. def mycommand(name=None,...):
  8209. Test it like this:
  8210. if name is None:
  8211. self.raise_tcl_error('Argument name is missing.')
  8212. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  8213. otherwise we will miss it and processing will silently continue.
  8214. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  8215. which is catched in exec_command and displayed in TCL shell console with red background.
  8216. Error in console is displayed with TCL trace.
  8217. This behavior works only within main thread,
  8218. errors with promissed tasks can be catched and detected only with log.
  8219. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  8220. TCL shell.
  8221. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  8222. '''
  8223. commands = {
  8224. 'help': {
  8225. 'fcn': shelp,
  8226. 'help': _("Shows list of commands.")
  8227. },
  8228. }
  8229. # Import/overwrite tcl commands as objects of TclCommand descendants
  8230. # This modifies the variable 'commands'.
  8231. tclCommands.register_all_commands(self, commands)
  8232. # Add commands to the tcl interpreter
  8233. for cmd in commands:
  8234. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  8235. # Make the tcl puts function return instead of print to stdout
  8236. self.tcl.eval('''
  8237. rename puts original_puts
  8238. proc puts {args} {
  8239. if {[llength $args] == 1} {
  8240. return "[lindex $args 0]"
  8241. } else {
  8242. eval original_puts $args
  8243. }
  8244. }
  8245. ''')
  8246. def setup_recent_items(self):
  8247. # TODO: Move this to constructor
  8248. icons = {
  8249. "gerber": "share/flatcam_icon16.png",
  8250. "excellon": "share/drill16.png",
  8251. 'geometry': "share/geometry16.png",
  8252. "cncjob": "share/cnc16.png",
  8253. "project": "share/project16.png",
  8254. "svg": "share/geometry16.png",
  8255. "dxf": "share/dxf16.png",
  8256. "pdf": "share/pdf32.png",
  8257. "image": "share/image16.png"
  8258. }
  8259. openers = {
  8260. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8261. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8262. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8263. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8264. 'project': self.open_project,
  8265. 'svg': self.import_svg,
  8266. 'dxf': self.import_dxf,
  8267. 'image': self.import_image,
  8268. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8269. }
  8270. # Open recent file for files
  8271. try:
  8272. f = open(self.data_path + '/recent.json')
  8273. except IOError:
  8274. App.log.error("Failed to load recent item list.")
  8275. self.inform.emit('[ERROR_NOTCL] %s' %
  8276. _("Failed to load recent item list."))
  8277. return
  8278. try:
  8279. self.recent = json.load(f)
  8280. except json.scanner.JSONDecodeError:
  8281. App.log.error("Failed to parse recent item list.")
  8282. self.inform.emit('[ERROR_NOTCL] %s' %
  8283. _("Failed to parse recent item list."))
  8284. f.close()
  8285. return
  8286. f.close()
  8287. # Open recent file for projects
  8288. try:
  8289. fp = open(self.data_path + '/recent_projects.json')
  8290. except IOError:
  8291. App.log.error("Failed to load recent project item list.")
  8292. self.inform.emit('[ERROR_NOTCL] %s' %
  8293. _("Failed to load recent projects item list."))
  8294. return
  8295. try:
  8296. self.recent_projects = json.load(fp)
  8297. except json.scanner.JSONDecodeError:
  8298. App.log.error("Failed to parse recent project item list.")
  8299. self.inform.emit('[ERROR_NOTCL] %s' %
  8300. _("Failed to parse recent project item list."))
  8301. fp.close()
  8302. return
  8303. fp.close()
  8304. # Closure needed to create callbacks in a loop.
  8305. # Otherwise late binding occurs.
  8306. def make_callback(func, fname):
  8307. def opener():
  8308. func(fname)
  8309. return opener
  8310. def reset_recent_files():
  8311. # Reset menu
  8312. self.ui.recent.clear()
  8313. self.recent = []
  8314. try:
  8315. f = open(self.data_path + '/recent.json', 'w')
  8316. except IOError:
  8317. App.log.error("Failed to open recent items file for writing.")
  8318. return
  8319. json.dump(self.recent, f)
  8320. def reset_recent_projects():
  8321. # Reset menu
  8322. self.ui.recent_projects.clear()
  8323. self.recent_projects = []
  8324. try:
  8325. fp = open(self.data_path + '/recent_projects.json', 'w')
  8326. except IOError:
  8327. App.log.error("Failed to open recent projects items file for writing.")
  8328. return
  8329. json.dump(self.recent, fp)
  8330. # Reset menu
  8331. self.ui.recent.clear()
  8332. self.ui.recent_projects.clear()
  8333. # Create menu items for projects
  8334. for recent in self.recent_projects:
  8335. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8336. if recent['kind'] == 'project':
  8337. try:
  8338. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8339. # Attach callback
  8340. o = make_callback(openers[recent["kind"]], recent['filename'])
  8341. action.triggered.connect(o)
  8342. self.ui.recent_projects.addAction(action)
  8343. except KeyError:
  8344. App.log.error("Unsupported file type: %s" % recent["kind"])
  8345. # Last action in Recent Files menu is one that Clear the content
  8346. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8347. clear_action_proj.triggered.connect(reset_recent_projects)
  8348. self.ui.recent_projects.addSeparator()
  8349. self.ui.recent_projects.addAction(clear_action_proj)
  8350. # Create menu items for files
  8351. for recent in self.recent:
  8352. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8353. if recent['kind'] != 'project':
  8354. try:
  8355. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8356. # Attach callback
  8357. o = make_callback(openers[recent["kind"]], recent['filename'])
  8358. action.triggered.connect(o)
  8359. self.ui.recent.addAction(action)
  8360. except KeyError:
  8361. App.log.error("Unsupported file type: %s" % recent["kind"])
  8362. # Last action in Recent Files menu is one that Clear the content
  8363. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8364. clear_action.triggered.connect(reset_recent_files)
  8365. self.ui.recent.addSeparator()
  8366. self.ui.recent.addAction(clear_action)
  8367. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8368. # self.ui.menufilerecent.set_submenu(recent_menu)
  8369. # recent_menu.show_all()
  8370. # self.ui.recent.show()
  8371. self.log.debug("Recent items list has been populated.")
  8372. def setup_component_editor(self):
  8373. # label = QtWidgets.QLabel("Choose an item from Project")
  8374. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8375. sel_title = QtWidgets.QTextEdit(
  8376. _('<b>Shortcut Key List</b>'))
  8377. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8378. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8379. settings = QSettings("Open Source", "FlatCAM")
  8380. if settings.contains("notebook_font_size"):
  8381. fsize = settings.value('notebook_font_size', type=int)
  8382. else:
  8383. fsize = 12
  8384. tsize = fsize + int(fsize / 2)
  8385. # selected_text = (_('''
  8386. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  8387. #
  8388. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8389. # The normal flow when working in FlatCAM is the following:</span></p>
  8390. #
  8391. # <ol>
  8392. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  8393. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8394. # even dragging and dropping the files on the GUI.<br />
  8395. # <br />
  8396. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  8397. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8398. # &nbsp;</li>
  8399. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  8400. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8401. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8402. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8403. # <br />
  8404. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  8405. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8406. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8407. # it even if it was out of focus.<br />
  8408. # <br />
  8409. # You can change the parameters in this screen and the flow direction is like this:<br />
  8410. # <br />
  8411. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  8412. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8413. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8414. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8415. # </ol>
  8416. #
  8417. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8418. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8419. # <strong>F3</strong>.</span></p>
  8420. #
  8421. # ''').format(fsize=fsize, tsize=tsize))
  8422. selected_text = '''
  8423. <p><span style="font-size:{tsize}px"><strong>%s</strong></span></p>
  8424. <p><span style="font-size:{fsize}px"><strong>%s</strong>:<br />
  8425. %s:</span></p>
  8426. <ol>
  8427. <li><span style="font-size:{fsize}px">%s menu&#39;s, %s.<br />
  8428. <br />
  8429. %s &amp; %s.</span><br />
  8430. &nbsp;</li>
  8431. <li><span style="font-size:{fsize}px">%s <strong>%s</strong> (%s), <strong>%s</strong> %s it-s %s.<br />
  8432. <br />
  8433. %s <strong>%s</strong> %s <strong>%s</strong> %s.<br />
  8434. <br />
  8435. %s:<br />
  8436. <br />
  8437. <strong>%s</strong> -&gt; %s -&gt; %s -&gt;<strong> %s </strong> -&gt; %s -&gt; %s -&gt;<strong> %s
  8438. </strong>-&gt; %s <strong>%s)&nbsp;</strong>-&gt; %s</span></li>
  8439. </ol>
  8440. <p><span style="font-size:{fsize}px">%s <strong>%s -&gt; %s</strong>&nbsp;%s it&#39;s %s:
  8441. <strong>F3</strong>.</span></p>
  8442. ''' % (
  8443. _("Selected Tab - Choose an Item from Project Tab"), _("Details"),
  8444. _("The normal flow when working in FlatCAM is the following"),
  8445. _("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the"),
  8446. _("toolbars, key shortcuts or even dragging and dropping the files on the GUI"),
  8447. _("You can also load a FlatCAM project by double clicking on the project file, drag"),
  8448. _("drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app"),
  8449. _("Once an object is available in the Project Tab, by selecting it and then focusing on"),
  8450. _("SELECTED TAB"), _("more simpler is to double click the object name in the Project Tab"),
  8451. _("SELECTED TAB"), _("will be updated with the object properties according to"),
  8452. _("kind: Gerber, Excellon, Geometry or CNCJob object"),
  8453. _("If the selection of the object is done on the canvas by single click instead, and the"),
  8454. _("SELECTED TAB"),
  8455. _("is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, "
  8456. "double clicking on the object on the canvas will bring the"),
  8457. _("SELECTED TAB"), _("and populate it even if it was out of focus"),
  8458. _("You can change the parameters in this screen and the flow direction is like this"),
  8459. _("Gerber/Excellon Object"), _("Change Parameter"), _("Generate Geometry"), _("Geometry Object"),
  8460. _("Add tools (change param in Selected Tab)"), _("Generate CNCJob"), _("CNCJob Object"),
  8461. _("Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in"), _("SELECTED TAB"),
  8462. _("Save GCode"), _("A list of key shortcuts is available through an menu entry in"), _("Help"),
  8463. _("Shortcuts List"), _("or through"), _("own key shortcut"),
  8464. )
  8465. sel_title.setText(selected_text)
  8466. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8467. self.ui.selected_scroll_area.setWidget(sel_title)
  8468. def setup_obj_classes(self):
  8469. """
  8470. Sets up application specifics on the FlatCAMObj class.
  8471. :return: None
  8472. """
  8473. FlatCAMObj.app = self
  8474. ObjectCollection.app = self
  8475. Gerber.app = self
  8476. Excellon.app = self
  8477. Geometry.app = self
  8478. CNCjob.app = self
  8479. FCProcess.app = self
  8480. FCProcessContainer.app = self
  8481. def version_check(self):
  8482. """
  8483. Checks for the latest version of the program. Alerts the
  8484. user if theirs is outdated. This method is meant to be run
  8485. in a separate thread.
  8486. :return: None
  8487. """
  8488. self.log.debug("version_check()")
  8489. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8490. full_url = App.version_url + \
  8491. "?s=" + str(self.defaults['global_serial']) + \
  8492. "&v=" + str(self.version) + \
  8493. "&os=" + str(self.os) + \
  8494. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  8495. else:
  8496. # no_stats dict; just so it won't break things on website
  8497. no_ststs_dict = {}
  8498. no_ststs_dict["global_ststs"] = {}
  8499. full_url = App.version_url + \
  8500. "?s=" + str(self.defaults['global_serial']) + \
  8501. "&v=" + str(self.version) + \
  8502. "&os=" + str(self.os) + \
  8503. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8504. App.log.debug("Checking for updates @ %s" % full_url)
  8505. # ## Get the data
  8506. try:
  8507. f = urllib.request.urlopen(full_url)
  8508. except:
  8509. # App.log.warning("Failed checking for latest version. Could not connect.")
  8510. self.log.warning("Failed checking for latest version. Could not connect.")
  8511. self.inform.emit('[WARNING_NOTCL] %s' %
  8512. _("Failed checking for latest version. Could not connect."))
  8513. return
  8514. try:
  8515. data = json.load(f)
  8516. except Exception as e:
  8517. App.log.error("Could not parse information about latest version.")
  8518. self.inform.emit('[ERROR_NOTCL] %s' %
  8519. _("Could not parse information about latest version."))
  8520. App.log.debug("json.load(): %s" % str(e))
  8521. f.close()
  8522. return
  8523. f.close()
  8524. # ## Latest version?
  8525. if self.version >= data["version"]:
  8526. App.log.debug("FlatCAM is up to date!")
  8527. self.inform.emit('[success] %s' %
  8528. _("FlatCAM is up to date!"))
  8529. return
  8530. App.log.debug("Newer version available.")
  8531. self.message.emit(
  8532. _("Newer Version Available"),
  8533. _("There is a newer version of FlatCAM available for download:\n\n") +
  8534. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  8535. _("info")
  8536. )
  8537. def on_plotcanvas_setup(self, container=None):
  8538. """
  8539. This is doing the setup for the plot area (VisPy canvas)
  8540. :param container: widget where to install the canvas
  8541. :return: None
  8542. """
  8543. if container:
  8544. plot_container = container
  8545. else:
  8546. plot_container = self.ui.right_layout
  8547. self.plotcanvas = PlotCanvas(plot_container, self)
  8548. # So it can receive key presses
  8549. self.plotcanvas.native.setFocus()
  8550. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  8551. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  8552. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8553. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  8554. # Keys over plot enabled
  8555. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  8556. self.app_cursor = self.plotcanvas.new_cursor()
  8557. self.app_cursor.enabled = False
  8558. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8559. def on_zoom_fit(self, event):
  8560. """
  8561. Callback for zoom-out request. This can be either from the corresponding
  8562. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8563. with axes limits from the geometry bounds of all objects.
  8564. :param event: Ignored.
  8565. :return: None
  8566. """
  8567. self.plotcanvas.fit_view()
  8568. def on_zoom_in(self):
  8569. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8570. def on_zoom_out(self):
  8571. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8572. def disable_all_plots(self):
  8573. self.report_usage("disable_all_plots()")
  8574. self.disable_plots(self.collection.get_list())
  8575. self.inform.emit('[success] %s' %
  8576. _("All plots disabled."))
  8577. def disable_other_plots(self):
  8578. self.report_usage("disable_other_plots()")
  8579. self.disable_plots(self.collection.get_non_selected())
  8580. self.inform.emit('[success] %s' %
  8581. _("All non selected plots disabled."))
  8582. def enable_all_plots(self):
  8583. self.report_usage("enable_all_plots()")
  8584. self.enable_plots(self.collection.get_list())
  8585. self.inform.emit('[success] %s' %
  8586. _("All plots enabled."))
  8587. def on_enable_sel_plots(self):
  8588. log.debug("App.on_enable_sel_plot()")
  8589. object_list = self.collection.get_selected()
  8590. self.enable_plots(objects=object_list)
  8591. self.inform.emit('[success] %s' %
  8592. _("Selected plots enabled..."))
  8593. def on_disable_sel_plots(self):
  8594. log.debug("App.on_disable_sel_plot()")
  8595. # self.inform.emit(_("Disabling plots ..."))
  8596. object_list = self.collection.get_selected()
  8597. self.disable_plots(objects=object_list)
  8598. self.inform.emit('[success] %s' %
  8599. _("Selected plots disabled..."))
  8600. def enable_plots(self, objects):
  8601. """
  8602. Disables plots
  8603. :param objects: list of Objects to be enabled
  8604. :return:
  8605. """
  8606. log.debug("Enabling plots ...")
  8607. # self.inform.emit(_("Working ..."))
  8608. for obj in objects:
  8609. if obj.options['plot'] is False:
  8610. obj.options.set_change_callback(lambda x: None)
  8611. obj.options['plot'] = True
  8612. obj.options.set_change_callback(obj.on_options_change)
  8613. def worker_task(objects):
  8614. with self.proc_container.new(_("Enabling plots ...")):
  8615. for obj in objects:
  8616. # obj.options['plot'] = True
  8617. if isinstance(obj, FlatCAMCNCjob):
  8618. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8619. else:
  8620. obj.plot(visible=True)
  8621. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8622. # self.plots_updated.emit()
  8623. def disable_plots(self, objects):
  8624. """
  8625. Disables plots
  8626. :param objects: list of Objects to be disabled
  8627. :return:
  8628. """
  8629. # if no objects selected then do nothing
  8630. if not self.collection.get_selected():
  8631. return
  8632. log.debug("Disabling plots ...")
  8633. # self.inform.emit(_("Working ..."))
  8634. for obj in objects:
  8635. if obj.options['plot'] is True:
  8636. obj.options.set_change_callback(lambda x: None)
  8637. obj.options['plot'] = False
  8638. obj.options.set_change_callback(obj.on_options_change)
  8639. try:
  8640. self.delete_selection_shape()
  8641. except Exception as e:
  8642. log.debug("App.disable_plots() --> %s" % str(e))
  8643. # self.plots_updated.emit()
  8644. def worker_task(objects):
  8645. with self.proc_container.new(_("Disabling plots ...")):
  8646. for obj in objects:
  8647. # obj.options['plot'] = True
  8648. if isinstance(obj, FlatCAMCNCjob):
  8649. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8650. else:
  8651. obj.plot(visible=False)
  8652. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8653. def toggle_plots(self, objects):
  8654. """
  8655. Toggle plots visibility
  8656. :param objects: list of Objects for which to be toggled the visibility
  8657. :return:
  8658. """
  8659. # if no objects selected then do nothing
  8660. if not self.collection.get_selected():
  8661. return
  8662. log.debug("Toggling plots ...")
  8663. self.inform.emit(_("Working ..."))
  8664. for obj in objects:
  8665. if obj.options['plot'] is False:
  8666. obj.options['plot'] = True
  8667. else:
  8668. obj.options['plot'] = False
  8669. self.plots_updated.emit()
  8670. def clear_plots(self):
  8671. objects = self.collection.get_list()
  8672. for obj in objects:
  8673. obj.clear(obj == objects[-1])
  8674. # Clear pool to free memory
  8675. self.clear_pool()
  8676. def generate_cnc_job(self, objects):
  8677. self.report_usage("generate_cnc_job()")
  8678. # for obj in objects:
  8679. # obj.generatecncjob()
  8680. for obj in objects:
  8681. obj.on_generatecnc_button_click()
  8682. def save_project(self, filename, quit_action=False):
  8683. """
  8684. Saves the current project to the specified file.
  8685. :param filename: Name of the file in which to save.
  8686. :type filename: str
  8687. :param quit_action: if the project saving will be followed by an app quit; boolean
  8688. :return: None
  8689. """
  8690. self.log.debug("save_project()")
  8691. self.save_in_progress = True
  8692. with self.proc_container.new(_("Saving FlatCAM Project")) as proc:
  8693. # Capture the latest changes
  8694. # Current object
  8695. try:
  8696. self.collection.get_active().read_form()
  8697. except:
  8698. self.log.debug("There was no active object")
  8699. pass
  8700. # Project options
  8701. self.options_read_form()
  8702. # Serialize the whole project
  8703. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8704. "options": self.options,
  8705. "version": self.version}
  8706. if self.defaults["global_save_compressed"] is True:
  8707. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8708. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8709. # # Write
  8710. f.write(g)
  8711. self.inform.emit('[success] %s: %s' %
  8712. (_("Project saved to"), filename))
  8713. else:
  8714. # Open file
  8715. try:
  8716. f = open(filename, 'w')
  8717. except IOError:
  8718. App.log.error("Failed to open file for saving: %s", filename)
  8719. return
  8720. # Write
  8721. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8722. f.close()
  8723. # verification of the saved project
  8724. # Open and parse
  8725. try:
  8726. saved_f = open(filename, 'r')
  8727. except IOError:
  8728. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8729. (_("Failed to verify project file"), filename, _("Retry to save it."))
  8730. )
  8731. return
  8732. try:
  8733. saved_d = json.load(saved_f, object_hook=dict2obj)
  8734. except:
  8735. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8736. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  8737. )
  8738. f.close()
  8739. return
  8740. saved_f.close()
  8741. if 'version' in saved_d:
  8742. self.inform.emit('[success] %s: %s' %
  8743. (_("Project saved to"), filename))
  8744. else:
  8745. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8746. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  8747. )
  8748. settings = QSettings("Open Source", "FlatCAM")
  8749. lock_state = self.ui.lock_action.isChecked()
  8750. settings.setValue('toolbar_lock', lock_state)
  8751. # This will write the setting to the platform specific storage.
  8752. del settings
  8753. # if quit:
  8754. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8755. # t.start()
  8756. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8757. def start_delayed_quit(self, delay, filename, should_quit=None):
  8758. """
  8759. :param delay: period of checking if project file size is more than zero; in seconds
  8760. :param filename: the name of the project file to be checked periodically for size more than zero
  8761. :param should_quit: if the task finished will be followed by an app quit; boolean
  8762. :return:
  8763. """
  8764. to_quit = should_quit
  8765. self.save_timer = QtCore.QTimer()
  8766. self.save_timer.setInterval(delay)
  8767. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8768. self.save_timer.start()
  8769. def check_project_file_size(self, filename, should_quit=None):
  8770. """
  8771. :param filename: the name of the project file to be checked periodically for size more than zero
  8772. :param should_quit: will quit the app if True; boolean
  8773. :return:
  8774. """
  8775. try:
  8776. if os.stat(filename).st_size > 0:
  8777. self.save_in_progress = False
  8778. self.save_timer.stop()
  8779. if should_quit:
  8780. self.app_quit.emit()
  8781. except Exception as e:
  8782. traceback.print_exc()
  8783. def on_options_app2project(self):
  8784. """
  8785. Callback for Options->Transfer Options->App=>Project. Copies options
  8786. from application defaults to project defaults.
  8787. :return: None
  8788. """
  8789. self.report_usage("on_options_app2project")
  8790. self.defaults_read_form()
  8791. self.options.update(self.defaults)
  8792. self.options_write_form()
  8793. def on_options_project2app(self):
  8794. """
  8795. Callback for Options->Transfer Options->Project=>App. Copies options
  8796. from project defaults to application defaults.
  8797. :return: None
  8798. """
  8799. self.report_usage("on_options_project2app")
  8800. self.options_read_form()
  8801. self.defaults.update(self.options)
  8802. self.defaults_write_form()
  8803. def on_options_project2object(self):
  8804. """
  8805. Callback for Options->Transfer Options->Project=>Object. Copies options
  8806. from project defaults to the currently selected object.
  8807. :return: None
  8808. """
  8809. self.report_usage("on_options_project2object")
  8810. self.options_read_form()
  8811. obj = self.collection.get_active()
  8812. if obj is None:
  8813. self.inform.emit('[WARNING_NOTCL] %s' %
  8814. _("No object selected."))
  8815. return
  8816. for option in self.options:
  8817. if option.find(obj.kind + "_") == 0:
  8818. oname = option[len(obj.kind) + 1:]
  8819. obj.options[oname] = self.options[option]
  8820. obj.to_form() # Update UI
  8821. def on_options_object2project(self):
  8822. """
  8823. Callback for Options->Transfer Options->Object=>Project. Copies options
  8824. from the currently selected object to project defaults.
  8825. :return: None
  8826. """
  8827. self.report_usage("on_options_object2project")
  8828. obj = self.collection.get_active()
  8829. if obj is None:
  8830. self.inform.emit('[WARNING_NOTCL] %s' %
  8831. _("No object selected."))
  8832. return
  8833. obj.read_form()
  8834. for option in obj.options:
  8835. if option in ['name']: # TODO: Handle this better...
  8836. continue
  8837. self.options[obj.kind + "_" + option] = obj.options[option]
  8838. self.options_write_form()
  8839. def on_options_object2app(self):
  8840. """
  8841. Callback for Options->Transfer Options->Object=>App. Copies options
  8842. from the currently selected object to application defaults.
  8843. :return: None
  8844. """
  8845. self.report_usage("on_options_object2app")
  8846. obj = self.collection.get_active()
  8847. if obj is None:
  8848. self.inform.emit('[WARNING_NOTCL] %s' %
  8849. _("No object selected."))
  8850. return
  8851. obj.read_form()
  8852. for option in obj.options:
  8853. if option in ['name']: # TODO: Handle this better...
  8854. continue
  8855. self.defaults[obj.kind + "_" + option] = obj.options[option]
  8856. self.defaults_write_form()
  8857. def on_options_app2object(self):
  8858. """
  8859. Callback for Options->Transfer Options->App=>Object. Copies options
  8860. from application defaults to the currently selected object.
  8861. :return: None
  8862. """
  8863. self.report_usage("on_options_app2object")
  8864. self.defaults_read_form()
  8865. obj = self.collection.get_active()
  8866. if obj is None:
  8867. self.inform.emit('[WARNING_NOTCL] %s' %
  8868. _("No object selected."))
  8869. return
  8870. for option in self.defaults:
  8871. if option.find(obj.kind + "_") == 0:
  8872. oname = option[len(obj.kind) + 1:]
  8873. obj.options[oname] = self.defaults[option]
  8874. obj.to_form() # Update UI
  8875. class ArgsThread(QtCore.QObject):
  8876. open_signal = pyqtSignal(list)
  8877. start = pyqtSignal()
  8878. if sys.platform == 'win32':
  8879. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8880. else:
  8881. address = ('/tmp/testipc', 'AF_UNIX')
  8882. def __init__(self):
  8883. super(ArgsThread, self).__init__()
  8884. self.start.connect(self.run)
  8885. def my_loop(self, address):
  8886. try:
  8887. listener = Listener(*address)
  8888. while True:
  8889. conn = listener.accept()
  8890. self.serve(conn)
  8891. except socket.error as e:
  8892. conn = Client(*address)
  8893. conn.send(sys.argv)
  8894. conn.send('close')
  8895. # close the current instance only if there are args
  8896. if len(sys.argv) > 1:
  8897. sys.exit()
  8898. def serve(self, conn):
  8899. while True:
  8900. msg = conn.recv()
  8901. if msg == 'close':
  8902. break
  8903. self.open_signal.emit(msg)
  8904. conn.close()
  8905. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8906. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8907. @pyqtSlot()
  8908. def run(self):
  8909. self.my_loop(self.address)
  8910. class GracefulException(Exception):
  8911. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  8912. def __init__(self):
  8913. super().__init__()
  8914. def __str__(self):
  8915. return ('\n\n%s' % _("The user requested a graceful exit of the current task."))
  8916. # end of file