FlatCAMApp.py 558 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317
  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 webbrowser
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import lzma
  16. import threading
  17. import shutil
  18. import stat
  19. from stat import S_IREAD, S_IRGRP, S_IROTH
  20. import subprocess
  21. import ctypes
  22. # import tkinter as tk
  23. # from PyQt5 import QtPrintSupport
  24. from reportlab.graphics import renderPDF
  25. from reportlab.pdfgen import canvas
  26. from reportlab.graphics import renderPM
  27. from reportlab.lib.units import inch, mm
  28. from reportlab.lib.pagesizes import landscape, portrait
  29. from contextlib import contextmanager
  30. import gc
  31. from xml.dom.minidom import parseString as parse_xml_string
  32. from multiprocessing.connection import Listener, Client
  33. from multiprocessing import Pool, cpu_count
  34. import socket
  35. from array import array
  36. import vispy.scene as scene
  37. # #######################################
  38. # # Imports part of FlatCAM ##
  39. # #######################################
  40. from ObjectCollection import *
  41. from FlatCAMObj import *
  42. from camlib import to_dict, dict2obj, ET, ParseError
  43. from flatcamGUI.PlotCanvas import *
  44. from flatcamGUI.PlotCanvasLegacy import *
  45. from flatcamGUI.FlatCAMGUI import *
  46. from FlatCAMCommon import LoudDict, BookmarkManager, ToolsDB
  47. from FlatCAMPostProc import load_preprocessors
  48. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  49. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  50. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  51. from flatcamEditors.FlatCAMTextEditor import TextEditor
  52. from flatcamParsers.ParseHPGL2 import HPGL2
  53. from FlatCAMProcess import *
  54. from FlatCAMWorkerStack import WorkerStack
  55. # from flatcamGUI.VisPyVisuals import Color
  56. from vispy.gloo.util import _screenshot
  57. from vispy.io import write_png
  58. from flatcamTools import *
  59. import tclCommands
  60. import gettext
  61. import FlatCAMTranslation as fcTranslate
  62. import builtins
  63. if sys.platform == 'win32':
  64. import winreg
  65. fcTranslate.apply_language('strings')
  66. if '_' not in builtins.__dict__:
  67. _ = gettext.gettext
  68. class App(QtCore.QObject):
  69. # ########################################
  70. # # App ###
  71. # ########################################
  72. """
  73. The main application class. The constructor starts the GUI.
  74. """
  75. # Get Cmd Line Options
  76. cmd_line_shellfile = ''
  77. cmd_line_shellvar = ''
  78. cmd_line_headless = None
  79. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  80. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  81. "FlatCam.py --headless=1"
  82. try:
  83. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  84. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  85. "shellvar=",
  86. "headless=",
  87. "multiprocessing-fork="])
  88. except getopt.GetoptError:
  89. print(cmd_line_help)
  90. sys.exit(2)
  91. for opt, arg in cmd_line_options:
  92. if opt == '-h':
  93. print(cmd_line_help)
  94. sys.exit()
  95. elif opt == '--shellfile':
  96. cmd_line_shellfile = arg
  97. elif opt == '--shellvar':
  98. cmd_line_shellvar = arg
  99. elif opt == '--headless':
  100. try:
  101. cmd_line_headless = eval(arg)
  102. except NameError:
  103. pass
  104. # ## Logging ###
  105. log = logging.getLogger('base')
  106. log.setLevel(logging.DEBUG)
  107. # log.setLevel(logging.WARNING)
  108. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  109. handler = logging.StreamHandler()
  110. handler.setFormatter(formatter)
  111. log.addHandler(handler)
  112. # ##########################################################################
  113. # ################## Version and VERSION DATE ##############################
  114. # ##########################################################################
  115. version = 8.99
  116. version_date = "2019/12/15"
  117. beta = True
  118. engine = '3D'
  119. # current date now
  120. date = str(datetime.today()).rpartition('.')[0]
  121. date = ''.join(c for c in date if c not in ':-')
  122. date = date.replace(' ', '_')
  123. # URL for update checks and statistics
  124. version_url = "http://flatcam.org/version"
  125. # App URL
  126. app_url = "http://flatcam.org"
  127. # Manual URL
  128. manual_url = "http://flatcam.org/manual/index.html"
  129. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  130. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  131. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  132. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  133. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  134. # this variable will hold the project status
  135. # if True it will mean that the project was modified and not saved
  136. should_we_save = False
  137. # flag is True if saving action has been triggered
  138. save_in_progress = False
  139. # ###########################################################################
  140. # ############################# Signals ################################
  141. # ###########################################################################
  142. # Inform the user
  143. # Handled by:
  144. # * App.info() --> Print on the status bar
  145. inform = QtCore.pyqtSignal(str)
  146. app_quit = QtCore.pyqtSignal()
  147. # General purpose background task
  148. worker_task = QtCore.pyqtSignal(dict)
  149. # File opened
  150. # Handled by:
  151. # * register_folder()
  152. # * register_recent()
  153. # Note: Setting the parameters to unicode does not seem
  154. # to have an effect. Then are received as Qstring
  155. # anyway.
  156. # File type and filename
  157. file_opened = QtCore.pyqtSignal(str, str)
  158. # File type and filename
  159. file_saved = QtCore.pyqtSignal(str, str)
  160. # Percentage of progress
  161. progress = QtCore.pyqtSignal(int)
  162. plots_updated = QtCore.pyqtSignal()
  163. # Emitted by new_object() and passes the new object as argument, plot flag.
  164. # on_object_created() adds the object to the collection, plots on appropriate flag
  165. # and emits new_object_available.
  166. object_created = QtCore.pyqtSignal(object, bool, bool)
  167. # Emitted when a object has been changed (like scaled, mirrored)
  168. object_changed = QtCore.pyqtSignal(object)
  169. # Emitted after object has been plotted.
  170. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  171. object_plotted = QtCore.pyqtSignal(object)
  172. # Emitted when a new object has been added or deleted from/to the collection
  173. object_status_changed = QtCore.pyqtSignal(object, str, str)
  174. message = QtCore.pyqtSignal(str, str, str)
  175. # Emmited when shell command is finished(one command only)
  176. shell_command_finished = QtCore.pyqtSignal(object)
  177. # Emitted when multiprocess pool has been recreated
  178. pool_recreated = QtCore.pyqtSignal(object)
  179. # Emitted when an unhandled exception happens
  180. # in the worker task.
  181. thread_exception = QtCore.pyqtSignal(object)
  182. # used to signal that there are arguments for the app
  183. args_at_startup = QtCore.pyqtSignal(list)
  184. # a reusable signal to replot a list of objects
  185. # should be disconnected after use so it can be reused
  186. replot_signal = pyqtSignal(list)
  187. def __init__(self, user_defaults=True):
  188. """
  189. Starts the application.
  190. :return: app
  191. :rtype: App
  192. """
  193. App.log.info("FlatCAM Starting...")
  194. self.main_thread = QtWidgets.QApplication.instance().thread()
  195. # ############################################################################
  196. # # ################# OS-specific ############################################
  197. # ############################################################################
  198. portable = False
  199. # Folder for user settings.
  200. if sys.platform == 'win32':
  201. # #########################################################################
  202. # Setup the listening thread for another instance launching with args #####
  203. # #########################################################################
  204. # make sure the thread is stored by using a self. otherwise it's garbage collected
  205. self.th = QtCore.QThread()
  206. self.th.start(priority=QtCore.QThread.LowestPriority)
  207. self.new_launch = ArgsThread()
  208. self.new_launch.open_signal[list].connect(self.on_startup_args)
  209. self.new_launch.moveToThread(self.th)
  210. self.new_launch.start.emit()
  211. from win32com.shell import shell, shellcon
  212. if platform.architecture()[0] == '32bit':
  213. App.log.debug("Win32!")
  214. else:
  215. App.log.debug("Win64!")
  216. # #########################################################################
  217. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  218. # #########################################################################
  219. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  220. try:
  221. with open(config_file, 'r'):
  222. pass
  223. except FileNotFoundError:
  224. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  225. try:
  226. with open(config_file, 'r') as f:
  227. try:
  228. for line in f:
  229. param = str(line).replace('\n', '').rpartition('=')
  230. if param[0] == 'portable':
  231. try:
  232. portable = eval(param[2])
  233. except NameError:
  234. portable = False
  235. if param[0] == 'headless':
  236. if param[2].lower() == 'true':
  237. self.cmd_line_headless = 1
  238. else:
  239. self.cmd_line_headless = None
  240. except Exception as e:
  241. log.debug('App.__init__() -->%s' % str(e))
  242. return
  243. except FileNotFoundError as e:
  244. log.debug(str(e))
  245. pass
  246. if portable is False:
  247. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  248. else:
  249. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  250. self.os = 'windows'
  251. else: # Linux/Unix/MacOS
  252. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  253. self.os = 'unix'
  254. # ##########################################################################
  255. # ################## Setup folders and files ###############################
  256. # ##########################################################################
  257. if not os.path.exists(self.data_path):
  258. os.makedirs(self.data_path)
  259. App.log.debug('Created data folder: ' + self.data_path)
  260. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  261. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  262. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  263. if not os.path.exists(self.preprocessorpaths):
  264. os.makedirs(self.preprocessorpaths)
  265. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  266. # create tools_db.FlatConfig file if there is none
  267. try:
  268. f = open(self.data_path + '/tools_db.FlatConfig')
  269. f.close()
  270. except IOError:
  271. App.log.debug('Creating empty tool_db.FlatConfig')
  272. f = open(self.data_path + '/tools_db.FlatConfig', 'w')
  273. json.dump({}, f)
  274. f.close()
  275. # create current_defaults.FlatConfig file if there is none
  276. try:
  277. f = open(self.data_path + '/current_defaults.FlatConfig')
  278. f.close()
  279. except IOError:
  280. App.log.debug('Creating empty current_defaults.FlatConfig')
  281. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  282. json.dump({}, f)
  283. f.close()
  284. # create factory_defaults.FlatConfig file if there is none
  285. try:
  286. f = open(self.data_path + '/factory_defaults.FlatConfig')
  287. f.close()
  288. except IOError:
  289. App.log.debug('Creating empty factory_defaults.FlatConfig')
  290. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  291. json.dump({}, f)
  292. f.close()
  293. # create a recent files json file if there is none
  294. try:
  295. f = open(self.data_path + '/recent.json')
  296. f.close()
  297. except IOError:
  298. App.log.debug('Creating empty recent.json')
  299. f = open(self.data_path + '/recent.json', 'w')
  300. json.dump([], f)
  301. f.close()
  302. # create a recent projects json file if there is none
  303. try:
  304. fp = open(self.data_path + '/recent_projects.json')
  305. fp.close()
  306. except IOError:
  307. App.log.debug('Creating empty recent_projects.json')
  308. fp = open(self.data_path + '/recent_projects.json', 'w')
  309. json.dump([], fp)
  310. fp.close()
  311. # Application directory. CHDIR to it. Otherwise, trying to load
  312. # GUI icons will fail as their path is relative.
  313. # This will fail under cx_freeze ...
  314. self.app_home = os.path.dirname(os.path.realpath(__file__))
  315. App.log.debug("Application path is " + self.app_home)
  316. App.log.debug("Started in " + os.getcwd())
  317. # cx_freeze workaround
  318. if os.path.isfile(self.app_home):
  319. self.app_home = os.path.dirname(self.app_home)
  320. os.chdir(self.app_home)
  321. # #################################################################################
  322. # #################### DEFAULTS - PREFERENCES STORAGE #############################
  323. # #################################################################################
  324. self.defaults = LoudDict()
  325. self.defaults.update({
  326. # Global APP Preferences
  327. "decimals_inch": 4,
  328. "decimals_metric": 4,
  329. "version": self.version,
  330. "first_run": True,
  331. "units": "MM",
  332. "global_serial": 0,
  333. "global_stats": dict(),
  334. "global_tabs_detachable": True,
  335. "global_graphic_engine": '3D',
  336. "global_app_level": 'b',
  337. "global_portable": False,
  338. "global_language": 'English',
  339. "global_version_check": True,
  340. "global_send_stats": True,
  341. "global_pan_button": '2',
  342. "global_mselect_key": 'Control',
  343. "global_project_at_startup": False,
  344. "global_systray_icon": True,
  345. "global_project_autohide": True,
  346. "global_toggle_tooltips": True,
  347. "global_worker_number": 2,
  348. "global_tolerance": 0.005,
  349. "global_open_style": True,
  350. "global_delete_confirmation": True,
  351. "global_compression_level": 3,
  352. "global_save_compressed": True,
  353. "global_machinist_setting": False,
  354. # Global GUI Preferences
  355. "global_gridx": 1.0,
  356. "global_gridy": 1.0,
  357. "global_snap_max": 0.05,
  358. "global_workspace": False,
  359. "global_workspaceT": "A4",
  360. "global_workspace_orientation": 'p',
  361. "global_grid_context_menu": {
  362. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  363. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  364. },
  365. "global_plot_fill": '#BBF268BF',
  366. "global_plot_line": '#006E20BF',
  367. "global_sel_fill": '#a5a5ffbf',
  368. "global_sel_line": '#0000ffbf',
  369. "global_alt_sel_fill": '#BBF268BF',
  370. "global_alt_sel_line": '#006E20BF',
  371. "global_draw_color": '#FF0000',
  372. "global_sel_draw_color": '#0000FF',
  373. "global_proj_item_color": '#000000',
  374. "global_proj_item_dis_color": '#b7b7cb',
  375. "global_activity_icon": 'Ball green',
  376. "global_toolbar_view": 511,
  377. "global_background_timeout": 300000, # Default value is 5 minutes
  378. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  379. # (python trace only for unknown errors),
  380. # 1 = show trace(show trace always),
  381. # 2 = (For the future).
  382. # Persistence
  383. "global_last_folder": None,
  384. "global_last_save_folder": None,
  385. # Default window geometry
  386. "global_def_win_x": 100,
  387. "global_def_win_y": 100,
  388. "global_def_win_w": 1024,
  389. "global_def_win_h": 650,
  390. "global_def_notebook_width": 1,
  391. # Constants...
  392. "global_defaults_save_period_ms": 20000, # Time between default saves.
  393. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  394. "global_shell_at_startup": False, # Show the shell at startup.
  395. "global_recent_limit": 10, # Max. items in recent list.
  396. "global_bookmarks": dict(),
  397. "global_bookmarks_limit": 10,
  398. "fit_key": 'V',
  399. "zoom_out_key": '-',
  400. "zoom_in_key": '=',
  401. "grid_toggle_key": 'G',
  402. "global_zoom_ratio": 1.5,
  403. "global_point_clipboard_format": "(%.4f, %.4f)",
  404. "global_zdownrate": None,
  405. # General GUI Settings
  406. "global_theme": 'white',
  407. "global_hover": False,
  408. "global_selection_shape": True,
  409. "global_layout": "compact",
  410. "global_cursor_type": "small",
  411. "global_cursor_size": 20,
  412. # Gerber General
  413. "gerber_plot": True,
  414. "gerber_solid": True,
  415. "gerber_multicolored": False,
  416. "gerber_circle_steps": 64,
  417. "gerber_use_buffer_for_union": True,
  418. "gerber_def_units": 'IN',
  419. "gerber_def_zeros": 'L',
  420. "gerber_save_filters": "Gerber File (*.gbr);;Gerber File (*.bot);;Gerber File (*.bsm);;"
  421. "Gerber File (*.cmp);;Gerber File (*.crc);;Gerber File (*.crs);;"
  422. "Gerber File (*.gb0);;Gerber File (*.gb1);;Gerber File (*.gb2);;"
  423. "Gerber File (*.gb3);;Gerber File (*.gb4);;Gerber File (*.gb5);;"
  424. "Gerber File (*.gb6);;Gerber File (*.gb7);;Gerber File (*.gb8);;"
  425. "Gerber File (*.gb9);;Gerber File (*.gbd);;Gerber File (*.gbl);;"
  426. "Gerber File (*.gbo);;Gerber File (*.gbp);;Gerber File (*.gbs);;"
  427. "Gerber File (*.gdo);;Gerber File (*.ger);;Gerber File (*.gko);;"
  428. "Gerber File (*.gm1);;Gerber File (*.gm2);;Gerber File (*.gm3);;"
  429. "Gerber File (*.grb);;Gerber File (*.gtl);;Gerber File (*.gto);;"
  430. "Gerber File (*.gtp);;Gerber File (*.gts);;Gerber File (*.ly15);;"
  431. "Gerber File (*.ly2);;Gerber File (*.mil);;Gerber File (*.pho);;"
  432. "Gerber File (*.plc);;Gerber File (*.pls);;Gerber File (*.smb);;"
  433. "Gerber File (*.smt);;Gerber File (*.sol);;Gerber File (*.spb);;"
  434. "Gerber File (*.spt);;Gerber File (*.ssb);;Gerber File (*.sst);;"
  435. "Gerber File (*.stc);;Gerber File (*.sts);;Gerber File (*.top);;"
  436. "Gerber File (*.tsm);;Gerber File (*.art)"
  437. "All Files (*.*)",
  438. # Gerber Options
  439. "gerber_isotooldia": 0.1,
  440. "gerber_isopasses": 1,
  441. "gerber_isooverlap": 10,
  442. "gerber_milling_type": "cl",
  443. "gerber_combine_passes": False,
  444. "gerber_iso_scope": 'all',
  445. "gerber_noncoppermargin": 0.1,
  446. "gerber_noncopperrounded": False,
  447. "gerber_bboxmargin": 0.1,
  448. "gerber_bboxrounded": False,
  449. # Gerber Advanced Options
  450. "gerber_aperture_display": False,
  451. "gerber_aperture_scale_factor": 1.0,
  452. "gerber_aperture_buffer_factor": 0.0,
  453. "gerber_follow": False,
  454. "gerber_tool_type": 'circular',
  455. "gerber_vtipdia": 0.1,
  456. "gerber_vtipangle": 30,
  457. "gerber_vcutz": -0.05,
  458. "gerber_iso_type": "full",
  459. "gerber_buffering": "full",
  460. "gerber_simplification": False,
  461. "gerber_simp_tolerance": 0.0005,
  462. # Gerber Export
  463. "gerber_exp_units": 'IN',
  464. "gerber_exp_integer": 2,
  465. "gerber_exp_decimals": 4,
  466. "gerber_exp_zeros": 'L',
  467. # Gerber Editor
  468. "gerber_editor_sel_limit": 30,
  469. "gerber_editor_newcode": 10,
  470. "gerber_editor_newsize": 0.8,
  471. "gerber_editor_newtype": 'C',
  472. "gerber_editor_newdim": "0.5, 0.5",
  473. "gerber_editor_array_size": 5,
  474. "gerber_editor_lin_axis": 'X',
  475. "gerber_editor_lin_pitch": 0.1,
  476. "gerber_editor_lin_angle": 0.0,
  477. "gerber_editor_circ_dir": 'CW',
  478. "gerber_editor_circ_angle": 0.0,
  479. "gerber_editor_scale_f": 1.0,
  480. "gerber_editor_buff_f": 0.1,
  481. "gerber_editor_ma_low": 0.0,
  482. "gerber_editor_ma_high": 1.0,
  483. # Excellon General
  484. "excellon_plot": True,
  485. "excellon_solid": True,
  486. "excellon_format_upper_in": 2,
  487. "excellon_format_lower_in": 4,
  488. "excellon_format_upper_mm": 3,
  489. "excellon_format_lower_mm": 3,
  490. "excellon_zeros": "L",
  491. "excellon_units": "INCH",
  492. "excellon_update": True,
  493. "excellon_optimization_type": 'B',
  494. "excellon_search_time": 3,
  495. "excellon_save_filters": "Excellon File (*.txt);;Excellon File (*.drd);;Excellon File (*.drl);;"
  496. "Excellon File (*.exc);;Excellon File (*.ncd);;Excellon File (*.tap);;"
  497. "Excellon File (*.xln);;All Files (*.*)",
  498. # Excellon Options
  499. "excellon_drillz": -1.7,
  500. "excellon_travelz": 2,
  501. "excellon_endz": 0.5,
  502. "excellon_feedrate": 300,
  503. "excellon_spindlespeed": 0,
  504. "excellon_dwell": False,
  505. "excellon_dwelltime": 1,
  506. "excellon_toolchange": False,
  507. "excellon_toolchangez": 15,
  508. "excellon_ppname_e": 'default',
  509. "excellon_tooldia": 0.8,
  510. "excellon_slot_tooldia": 1.8,
  511. "excellon_gcode_type": "drills",
  512. # Excellon Advanced Options
  513. "excellon_offset": 0.0,
  514. "excellon_toolchangexy": "0.0, 0.0",
  515. "excellon_startz": None,
  516. "excellon_feedrate_rapid": 1500,
  517. "excellon_z_pdepth": -0.02,
  518. "excellon_feedrate_probe": 75,
  519. "excellon_spindledir": 'CW',
  520. "excellon_f_plunge": False,
  521. "excellon_f_retract": False,
  522. # Excellon Export
  523. "excellon_exp_units": 'INCH',
  524. "excellon_exp_format": 'ndec',
  525. "excellon_exp_integer": 2,
  526. "excellon_exp_decimals": 4,
  527. "excellon_exp_zeros": 'LZ',
  528. "excellon_exp_slot_type": 'routing',
  529. # Excellon Editor
  530. "excellon_editor_sel_limit": 30,
  531. "excellon_editor_newdia": 1.0,
  532. "excellon_editor_array_size": 5,
  533. "excellon_editor_lin_dir": 'X',
  534. "excellon_editor_lin_pitch": 2.54,
  535. "excellon_editor_lin_angle": 0.0,
  536. "excellon_editor_circ_dir": 'CW',
  537. "excellon_editor_circ_angle": 12,
  538. # Excellon Slots
  539. "excellon_editor_slot_direction": 'X',
  540. "excellon_editor_slot_angle": 0.0,
  541. "excellon_editor_slot_length": 5.0,
  542. # Excellon Slot Array
  543. "excellon_editor_slot_array_size": 5,
  544. "excellon_editor_slot_lin_dir": 'X',
  545. "excellon_editor_slot_lin_pitch": 2.54,
  546. "excellon_editor_slot_lin_angle": 0.0,
  547. "excellon_editor_slot_circ_dir": 'CW',
  548. "excellon_editor_slot_circ_angle": 0.0,
  549. # Geometry General
  550. "geometry_plot": True,
  551. "geometry_circle_steps": 64,
  552. "geometry_cnctooldia": "2.4",
  553. # Geometry Options
  554. "geometry_cutz": -2.4,
  555. "geometry_vtipdia": 0.1,
  556. "geometry_vtipangle": 30,
  557. "geometry_multidepth": False,
  558. "geometry_depthperpass": 0.8,
  559. "geometry_travelz": 2,
  560. "geometry_toolchange": False,
  561. "geometry_toolchangez": 15.0,
  562. "geometry_endz": 15.0,
  563. "geometry_feedrate": 120,
  564. "geometry_feedrate_z": 60,
  565. "geometry_spindlespeed": 0,
  566. "geometry_dwell": False,
  567. "geometry_dwelltime": 1,
  568. "geometry_ppname_g": 'default',
  569. # Geometry Advanced Options
  570. "geometry_toolchangexy": "0.0, 0.0",
  571. "geometry_startz": None,
  572. "geometry_feedrate_rapid": 1500,
  573. "geometry_extracut": False,
  574. "geometry_extracut_length": 0.1,
  575. "geometry_z_pdepth": -0.02,
  576. "geometry_f_plunge": False,
  577. "geometry_spindledir": 'CW',
  578. "geometry_feedrate_probe": 75,
  579. "geometry_segx": 0.0,
  580. "geometry_segy": 0.0,
  581. # Geometry Editor
  582. "geometry_editor_sel_limit": 30,
  583. "geometry_editor_milling_type": "cl",
  584. # CNC Job General
  585. "cncjob_plot": True,
  586. "cncjob_plot_kind": 'all',
  587. "cncjob_annotation": True,
  588. "cncjob_tooldia": 1.0,
  589. "cncjob_coords_type": "G90",
  590. "cncjob_coords_decimals": 4,
  591. "cncjob_fr_decimals": 2,
  592. "cncjob_steps_per_circle": 64,
  593. "cncjob_footer": False,
  594. "cncjob_line_ending": False,
  595. "cncjob_save_filters": "G-Code Files (*.nc);;G-Code Files (*.din);;G-Code Files (*.dnc);;"
  596. "G-Code Files (*.ecs);;G-Code Files (*.eia);;G-Code Files (*.fan);;"
  597. "G-Code Files (*.fgc);;G-Code Files (*.fnc);;G-Code Files (*.gc);;"
  598. "G-Code Files (*.gcd);;G-Code Files (*.gcode);;G-Code Files (*.h);;"
  599. "G-Code Files (*.hnc);;G-Code Files (*.i);;G-Code Files (*.min);;"
  600. "G-Code Files (*.mpf);;G-Code Files (*.mpr);;G-Code Files (*.cnc);;"
  601. "G-Code Files (*.ncc);;G-Code Files (*.ncg);;G-Code Files (*.ncp);;"
  602. "G-Code Files (*.ngc);;G-Code Files (*.out);;G-Code Files (*.ply);;"
  603. "G-Code Files (*.sbp);;G-Code Files (*.tap);;G-Code Files (*.xpi);;"
  604. "All Files (*.*)",
  605. # CNC Job Options
  606. "cncjob_prepend": "",
  607. "cncjob_append": "",
  608. # CNC Job Advanced Options
  609. "cncjob_toolchange_macro": "",
  610. "cncjob_toolchange_macro_enable": False,
  611. "cncjob_annotation_fontsize": 9,
  612. "cncjob_annotation_fontcolor": '#990000',
  613. # NCC Tool
  614. "tools_ncctools": "1.0, 0.5",
  615. "tools_nccorder": 'rev',
  616. "tools_nccoverlap": 40,
  617. "tools_nccmargin": 1.0,
  618. "tools_nccmethod": "seed",
  619. "tools_nccconnect": True,
  620. "tools_ncccontour": True,
  621. "tools_nccrest": False,
  622. "tools_ncc_offset_choice": False,
  623. "tools_ncc_offset_value": 0.0000,
  624. "tools_nccref": 'itself',
  625. "tools_ncc_plotting": 'normal',
  626. "tools_nccmilling_type": 'cl',
  627. "tools_ncctool_type": 'V',
  628. "tools_ncccutz": -0.05,
  629. "tools_ncctipdia": 0.1,
  630. "tools_ncctipangle": 30,
  631. "tools_nccnewdia": 1.0,
  632. # Cutout Tool
  633. "tools_cutouttooldia": 2.4,
  634. "tools_cutoutkind": "single",
  635. "tools_cutoutmargin": 0.1,
  636. "tools_cutout_z": -1.8,
  637. "tools_cutout_depthperpass": 0.6,
  638. "tools_cutout_mdepth": True,
  639. "tools_cutoutgapsize": 4,
  640. "tools_gaps_ff": "4",
  641. "tools_cutout_convexshape": False,
  642. # Paint Tool
  643. "tools_painttooldia": 0.3,
  644. "tools_paintorder": 'rev',
  645. "tools_paintoverlap": 20,
  646. "tools_paintmargin": 0.0,
  647. "tools_paintmethod": "seed",
  648. "tools_selectmethod": "all",
  649. "tools_pathconnect": True,
  650. "tools_paintcontour": True,
  651. "tools_paint_plotting": 'normal',
  652. # 2-Sided Tool
  653. "tools_2sided_mirror_axis": "X",
  654. "tools_2sided_axis_loc": "point",
  655. "tools_2sided_drilldia": 3.125,
  656. # Film Tool
  657. "tools_film_type": 'neg',
  658. "tools_film_boundary": 1.0,
  659. "tools_film_scale_stroke": 0,
  660. "tools_film_color": '#000000',
  661. "tools_film_scale_cb": False,
  662. "tools_film_scale_x_entry": 1.0,
  663. "tools_film_scale_y_entry": 1.0,
  664. "tools_film_skew_cb": False,
  665. "tools_film_skew_x_entry": 0.0,
  666. "tools_film_skew_y_entry": 0.0,
  667. "tools_film_skew_ref_radio": 'bottomleft',
  668. "tools_film_mirror_cb": False,
  669. "tools_film_mirror_axis_radio": 'none',
  670. "tools_film_file_type_radio": 'svg',
  671. "tools_film_orientation": 'p',
  672. "tools_film_pagesize": 'A4',
  673. # Panel Tool
  674. "tools_panelize_spacing_columns": 0,
  675. "tools_panelize_spacing_rows": 0,
  676. "tools_panelize_columns": 1,
  677. "tools_panelize_rows": 1,
  678. "tools_panelize_constrain": False,
  679. "tools_panelize_constrainx": 200.0,
  680. "tools_panelize_constrainy": 290.0,
  681. "tools_panelize_panel_type": 'gerber',
  682. # Calculators Tool
  683. "tools_calc_vshape_tip_dia": 0.2,
  684. "tools_calc_vshape_tip_angle": 30,
  685. "tools_calc_vshape_cut_z": 0.05,
  686. "tools_calc_electro_length": 10.0,
  687. "tools_calc_electro_width": 10.0,
  688. "tools_calc_electro_cdensity": 13.0,
  689. "tools_calc_electro_growth": 10.0,
  690. # Transform Tool
  691. "tools_transform_rotate": 90,
  692. "tools_transform_skew_x": 0.0,
  693. "tools_transform_skew_y": 0.0,
  694. "tools_transform_scale_x": 1.0,
  695. "tools_transform_scale_y": 1.0,
  696. "tools_transform_scale_link": True,
  697. "tools_transform_scale_reference": True,
  698. "tools_transform_offset_x": 0.0,
  699. "tools_transform_offset_y": 0.0,
  700. "tools_transform_mirror_reference": False,
  701. "tools_transform_mirror_point": (0, 0),
  702. # SolderPaste Tool
  703. "tools_solderpaste_tools": "1.0, 0.3",
  704. "tools_solderpaste_new": 0.3,
  705. "tools_solderpaste_z_start": 0.05,
  706. "tools_solderpaste_z_dispense": 0.1,
  707. "tools_solderpaste_z_stop": 0.05,
  708. "tools_solderpaste_z_travel": 0.1,
  709. "tools_solderpaste_z_toolchange": 1.0,
  710. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  711. "tools_solderpaste_frxy": 150,
  712. "tools_solderpaste_frz": 150,
  713. "tools_solderpaste_frz_dispense": 1.0,
  714. "tools_solderpaste_speedfwd": 300,
  715. "tools_solderpaste_dwellfwd": 1,
  716. "tools_solderpaste_speedrev": 200,
  717. "tools_solderpaste_dwellrev": 1,
  718. "tools_solderpaste_pp": 'Paste_1',
  719. # Subtract Tool
  720. "tools_sub_close_paths": True,
  721. # ###################################################################################
  722. # ################################ TOOLS 2 ##########################################
  723. # ###################################################################################
  724. # Optimal Tool
  725. "tools_opt_precision": 4,
  726. # Check Rules Tool
  727. "tools_cr_trace_size": True,
  728. "tools_cr_trace_size_val": 0.25,
  729. "tools_cr_c2c": True,
  730. "tools_cr_c2c_val": 0.25,
  731. "tools_cr_c2o": True,
  732. "tools_cr_c2o_val": 1.0,
  733. "tools_cr_s2s": True,
  734. "tools_cr_s2s_val": 0.25,
  735. "tools_cr_s2sm": True,
  736. "tools_cr_s2sm_val": 0.25,
  737. "tools_cr_s2o": True,
  738. "tools_cr_s2o_val": 1.0,
  739. "tools_cr_sm2sm": True,
  740. "tools_cr_sm2sm_val": 0.25,
  741. "tools_cr_ri": True,
  742. "tools_cr_ri_val": 0.3,
  743. "tools_cr_h2h": True,
  744. "tools_cr_h2h_val": 0.3,
  745. "tools_cr_dh": True,
  746. "tools_cr_dh_val": 0.3,
  747. # QRCode Tool
  748. "tools_qrcode_version": 1,
  749. "tools_qrcode_error": 'L',
  750. "tools_qrcode_box_size": 3,
  751. "tools_qrcode_border_size": 4,
  752. "tools_qrcode_qrdata": '',
  753. "tools_qrcode_polarity": 'pos',
  754. "tools_qrcode_rounded": 's',
  755. "tools_qrcode_fill_color": '#000000',
  756. "tools_qrcode_back_color": '#FFFFFF',
  757. "tools_qrcode_sel_limit": 330,
  758. # Copper Thieving Tool
  759. "tools_copper_thieving_clearance": 0.25,
  760. "tools_copper_thieving_margin": 1.0,
  761. "tools_copper_thieving_reference": 'itself',
  762. "tools_copper_thieving_box_type": 'rect',
  763. "tools_copper_thieving_circle_steps": 64,
  764. "tools_copper_thieving_fill_type": 'solid',
  765. "tools_copper_thieving_dots_dia": 1.0,
  766. "tools_copper_thieving_dots_spacing": 2.0,
  767. "tools_copper_thieving_squares_size": 1.0,
  768. "tools_copper_thieving_squares_spacing": 2.0,
  769. "tools_copper_thieving_lines_size": 0.25,
  770. "tools_copper_thieving_lines_spacing": 2.0,
  771. "tools_copper_thieving_rb_margin": 1.0,
  772. "tools_copper_thieving_rb_thickness": 1.0,
  773. "tools_copper_thieving_mask_clearance": 0.0,
  774. # Fiducials Tool
  775. "tools_fiducials_dia": 1.0,
  776. "tools_fiducials_margin": 1.0,
  777. "tools_fiducials_mode": 'auto',
  778. "tools_fiducials_second_pos": 'up',
  779. "tools_fiducials_type": 'circular',
  780. "tools_fiducials_line_thickness": 0.25,
  781. # Calibration Tool
  782. "tools_cal_calsource": 'object',
  783. "tools_cal_travelz": 2.0,
  784. "tools_cal_verz": 0.1,
  785. "tools_cal_zeroz": False,
  786. "tools_cal_toolchangez": 15,
  787. "tools_cal_toolchange_xy": '',
  788. "tools_cal_sec_point": 'tl',
  789. # Utilities
  790. # file associations
  791. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  792. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  793. 'ncg, ncp, ngc, out, ply, rol, sbp, tap, xpi',
  794. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, gb0, gb1, gb2, gb3, gb4, gb5, gb6, gb7, gb8, gb9, gbd, '
  795. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  796. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  797. # Keyword list
  798. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  799. 'Repetier, Roland_MDX_20, Users, Toolchange_Custom, Toolchange_Probe_MACH3, '
  800. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, auto, axisoffset, '
  801. 'box, center_x, center_y, columns, combine, connect, contour, default, '
  802. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  803. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  804. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  805. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  806. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  807. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  808. 'toolchange_xy, tooldia, use_threads, value, x, x0, x1, y, y0, y1, z_cut, '
  809. 'z_move',
  810. "script_autocompleter": True,
  811. "script_text": "",
  812. "script_plot": True,
  813. "script_source_file": "",
  814. "document_autocompleter": False,
  815. "document_text": "",
  816. "document_plot": True,
  817. "document_source_file": "",
  818. "document_font_color": '#000000',
  819. "document_sel_color": '#0055ff',
  820. "document_font_size": 6,
  821. "document_tab_size": 80,
  822. })
  823. # ############################################################
  824. # ############### Load defaults from file ####################
  825. # ############################################################
  826. self.old_defaults_found = False
  827. if user_defaults:
  828. self.load_defaults(filename='current_defaults')
  829. if self.defaults['units'] == 'MM':
  830. self.decimals = int(self.defaults['decimals_metric'])
  831. else:
  832. self.decimals = int(self.defaults['decimals_inch'])
  833. if self.defaults["global_theme"] == 'white':
  834. self.resource_location = 'share'
  835. else:
  836. self.resource_location = 'share'
  837. self.current_units = self.defaults['units']
  838. # #############################################################################
  839. # ##################### CREATE MULTIPROCESSING POOL ###########################
  840. # #############################################################################
  841. self.pool = Pool(processes=cpu_count())
  842. # ##########################################################################
  843. # ################## Setting the Splash Screen #############################
  844. # ##########################################################################
  845. splash_settings = QSettings("Open Source", "FlatCAM")
  846. if splash_settings.contains("splash_screen"):
  847. show_splash = splash_settings.value("splash_screen")
  848. else:
  849. splash_settings.setValue('splash_screen', 1)
  850. # This will write the setting to the platform specific storage.
  851. del splash_settings
  852. show_splash = 1
  853. if show_splash and self.cmd_line_headless != 1:
  854. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  855. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  856. # self.splash.setMask(splash_pix.mask())
  857. # move splashscreen to the current monitor
  858. desktop = QtWidgets.QApplication.desktop()
  859. screen = desktop.screenNumber(QtGui.QCursor.pos())
  860. current_screen_center = desktop.availableGeometry(screen).center()
  861. self.splash.move(current_screen_center - self.splash.rect().center())
  862. self.splash.show()
  863. self.splash.showMessage(_("FlatCAM is initializing ..."),
  864. alignment=Qt.AlignBottom | Qt.AlignLeft,
  865. color=QtGui.QColor("gray"))
  866. else:
  867. show_splash = 0
  868. # #############################################################################
  869. # ##################### Initialize GUI ########################################
  870. # #############################################################################
  871. # FlatCAM colors used in plotting
  872. self.FC_light_green = '#BBF268BF'
  873. self.FC_dark_green = '#006E20BF'
  874. self.FC_light_blue = '#a5a5ffbf'
  875. self.FC_dark_blue = '#0000ffbf'
  876. QtCore.QObject.__init__(self)
  877. self.ui = FlatCAMGUI(self)
  878. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  879. if theme_settings.contains("theme"):
  880. theme = theme_settings.value('theme', type=str)
  881. else:
  882. theme = 'white'
  883. if theme == 'white':
  884. self.cursor_color_3D = 'black'
  885. else:
  886. self.cursor_color_3D = 'gray'
  887. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  888. self.ui.final_save.connect(self.final_save)
  889. # restore the toolbar view
  890. self.restore_toolbar_view()
  891. # restore the GUI geometry
  892. self.restore_main_win_geom()
  893. # set FlatCAM units in the Status bar
  894. self.set_screen_units(self.defaults['units'])
  895. # #############################################################################
  896. # ######################## UPDATE PREFERENCES GUI FORMS #######################
  897. # #############################################################################
  898. # when adding entries here read the comments in the method found bellow named:
  899. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  900. self.defaults_form_fields = {
  901. # General App
  902. "decimals_inch": self.ui.general_defaults_form.general_app_group.precision_inch_entry,
  903. "decimals_metric": self.ui.general_defaults_form.general_app_group.precision_metric_entry,
  904. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  905. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  906. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  907. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  908. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  909. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  910. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  911. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  912. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  913. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  914. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  915. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  916. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_spinner,
  917. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  918. "global_bookmarks_limit": self.ui.general_defaults_form.general_app_group.bm_limit_spinner,
  919. "global_machinist_setting": self.ui.general_defaults_form.general_app_group.machinist_cb,
  920. # General GUI Preferences
  921. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  922. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  923. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  924. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  925. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  926. "global_workspace_orientation": self.ui.general_defaults_form.general_gui_group.wk_orientation_radio,
  927. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  928. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  929. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  930. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  931. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  932. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  933. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  934. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  935. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  936. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  937. "global_activity_icon": self.ui.general_defaults_form.general_gui_group.activity_combo,
  938. # General GUI Settings
  939. "global_theme": self.ui.general_defaults_form.general_gui_set_group.theme_radio,
  940. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  941. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  942. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  943. "global_systray_icon": self.ui.general_defaults_form.general_gui_set_group.systray_cb,
  944. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  945. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  946. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  947. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  948. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  949. "global_cursor_type": self.ui.general_defaults_form.general_gui_set_group.cursor_radio,
  950. "global_cursor_size": self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry,
  951. # Gerber General
  952. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  953. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  954. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  955. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  956. "gerber_def_units": self.ui.gerber_defaults_form.gerber_gen_group.gerber_units_radio,
  957. "gerber_def_zeros": self.ui.gerber_defaults_form.gerber_gen_group.gerber_zeros_radio,
  958. # Gerber Options
  959. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  960. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  961. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  962. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  963. "gerber_iso_scope": self.ui.gerber_defaults_form.gerber_opt_group.iso_scope_radio,
  964. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  965. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  966. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  967. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  968. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  969. # Gerber Advanced Options
  970. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  971. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  972. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  973. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  974. "gerber_tool_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.tool_type_radio,
  975. "gerber_vtipdia": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipdia_spinner,
  976. "gerber_vtipangle": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipangle_spinner,
  977. "gerber_vcutz": self.ui.gerber_defaults_form.gerber_adv_opt_group.cutz_spinner,
  978. "gerber_iso_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.iso_type_radio,
  979. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  980. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  981. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  982. # Gerber Export
  983. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  984. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  985. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  986. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  987. # Gerber Editor
  988. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  989. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  990. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  991. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  992. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  993. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  994. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  995. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  996. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  997. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  998. "gerber_editor_circ_angle":
  999. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  1000. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  1001. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  1002. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  1003. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  1004. # Excellon General
  1005. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  1006. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  1007. "excellon_format_upper_in":
  1008. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  1009. "excellon_format_lower_in":
  1010. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  1011. "excellon_format_upper_mm":
  1012. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1013. "excellon_format_lower_mm":
  1014. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1015. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  1016. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  1017. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  1018. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  1019. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  1020. # Excellon Options
  1021. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  1022. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  1023. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  1024. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  1025. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  1026. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  1027. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  1028. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  1029. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  1030. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  1031. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  1032. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  1033. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  1034. # Excellon Advanced Options
  1035. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  1036. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  1037. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  1038. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1039. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  1040. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  1041. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  1042. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  1043. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  1044. # Excellon Export
  1045. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  1046. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  1047. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  1048. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  1049. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  1050. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  1051. # Excellon Editor
  1052. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  1053. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  1054. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  1055. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  1056. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  1057. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  1058. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  1059. "excellon_editor_circ_angle":
  1060. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  1061. # Excellon Slots
  1062. "excellon_editor_slot_direction":
  1063. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  1064. "excellon_editor_slot_angle":
  1065. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  1066. "excellon_editor_slot_length":
  1067. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  1068. # Excellon Slots
  1069. "excellon_editor_slot_array_size":
  1070. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  1071. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  1072. "excellon_editor_slot_lin_pitch":
  1073. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  1074. "excellon_editor_slot_lin_angle":
  1075. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  1076. "excellon_editor_slot_circ_dir":
  1077. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  1078. "excellon_editor_slot_circ_angle":
  1079. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  1080. # Geometry General
  1081. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  1082. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  1083. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  1084. # Geometry Options
  1085. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  1086. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  1087. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  1088. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  1089. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  1090. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  1091. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  1092. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  1093. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  1094. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  1095. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  1096. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  1097. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  1098. # Geometry Advanced Options
  1099. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  1100. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  1101. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1102. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  1103. "geometry_extracut_length": self.ui.geometry_defaults_form.geometry_adv_opt_group.e_cut_entry,
  1104. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  1105. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  1106. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  1107. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  1108. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  1109. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  1110. # Geometry Editor
  1111. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  1112. "geometry_editor_milling_type": self.ui.geometry_defaults_form.geometry_editor_group.milling_type_radio,
  1113. # CNCJob General
  1114. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  1115. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  1116. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  1117. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  1118. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  1119. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  1120. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  1121. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  1122. "cncjob_line_ending": self.ui.cncjob_defaults_form.cncjob_gen_group.line_ending_cb,
  1123. # CNC Job Options
  1124. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  1125. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  1126. # CNC Job Advanced Options
  1127. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  1128. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  1129. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  1130. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  1131. # NCC Tool
  1132. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  1133. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  1134. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  1135. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  1136. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  1137. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  1138. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  1139. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  1140. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  1141. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  1142. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  1143. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  1144. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  1145. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  1146. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  1147. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  1148. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  1149. "tools_nccnewdia": self.ui.tools_defaults_form.tools_ncc_group.newdia_entry,
  1150. # CutOut Tool
  1151. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  1152. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  1153. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  1154. "tools_cutout_z": self.ui.tools_defaults_form.tools_cutout_group.cutz_entry,
  1155. "tools_cutout_depthperpass": self.ui.tools_defaults_form.tools_cutout_group.maxdepth_entry,
  1156. "tools_cutout_mdepth": self.ui.tools_defaults_form.tools_cutout_group.mpass_cb,
  1157. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  1158. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  1159. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  1160. # Paint Area Tool
  1161. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  1162. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  1163. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  1164. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  1165. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  1166. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  1167. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  1168. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  1169. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  1170. # 2-sided Tool
  1171. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  1172. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  1173. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  1174. # Film Tool
  1175. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  1176. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  1177. "tools_film_scale_stroke": self.ui.tools_defaults_form.tools_film_group.film_scale_stroke_entry,
  1178. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  1179. "tools_film_scale_cb": self.ui.tools_defaults_form.tools_film_group.film_scale_cb,
  1180. "tools_film_scale_x_entry": self.ui.tools_defaults_form.tools_film_group.film_scalex_entry,
  1181. "tools_film_scale_y_entry": self.ui.tools_defaults_form.tools_film_group.film_scaley_entry,
  1182. "tools_film_skew_cb": self.ui.tools_defaults_form.tools_film_group.film_skew_cb,
  1183. "tools_film_skew_x_entry": self.ui.tools_defaults_form.tools_film_group.film_skewx_entry,
  1184. "tools_film_skew_y_entry": self.ui.tools_defaults_form.tools_film_group.film_skewy_entry,
  1185. "tools_film_skew_ref_radio": self.ui.tools_defaults_form.tools_film_group.film_skew_reference,
  1186. "tools_film_mirror_cb": self.ui.tools_defaults_form.tools_film_group.film_mirror_cb,
  1187. "tools_film_mirror_axis_radio": self.ui.tools_defaults_form.tools_film_group.film_mirror_axis,
  1188. "tools_film_file_type_radio": self.ui.tools_defaults_form.tools_film_group.file_type_radio,
  1189. "tools_film_orientation": self.ui.tools_defaults_form.tools_film_group.orientation_radio,
  1190. "tools_film_pagesize": self.ui.tools_defaults_form.tools_film_group.pagesize_combo,
  1191. # Panelize Tool
  1192. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  1193. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  1194. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  1195. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  1196. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  1197. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  1198. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  1199. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  1200. # Calculators Tool
  1201. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  1202. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  1203. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  1204. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  1205. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  1206. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  1207. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  1208. # Transformations Tool
  1209. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  1210. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  1211. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  1212. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  1213. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  1214. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  1215. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  1216. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  1217. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  1218. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  1219. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  1220. # SolderPaste Dispensing Tool
  1221. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  1222. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  1223. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  1224. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  1225. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  1226. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  1227. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  1228. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  1229. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  1230. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  1231. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  1232. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  1233. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  1234. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  1235. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  1236. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  1237. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  1238. # ###################################################################################
  1239. # ################################ TOOLS 2 ##########################################
  1240. # ###################################################################################
  1241. # Optimal Tool
  1242. "tools_opt_precision": self.ui.tools2_defaults_form.tools2_optimal_group.precision_sp,
  1243. # Check Rules Tool
  1244. "tools_cr_trace_size": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_cb,
  1245. "tools_cr_trace_size_val": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_entry,
  1246. "tools_cr_c2c": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_cb,
  1247. "tools_cr_c2c_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_entry,
  1248. "tools_cr_c2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_cb,
  1249. "tools_cr_c2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_entry,
  1250. "tools_cr_s2s": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_cb,
  1251. "tools_cr_s2s_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_entry,
  1252. "tools_cr_s2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_cb,
  1253. "tools_cr_s2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_entry,
  1254. "tools_cr_s2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_cb,
  1255. "tools_cr_s2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_entry,
  1256. "tools_cr_sm2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_cb,
  1257. "tools_cr_sm2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_entry,
  1258. "tools_cr_ri": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_cb,
  1259. "tools_cr_ri_val": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_entry,
  1260. "tools_cr_h2h": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_cb,
  1261. "tools_cr_h2h_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_entry,
  1262. "tools_cr_dh": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_cb,
  1263. "tools_cr_dh_val": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_entry,
  1264. # QRCode Tool
  1265. "tools_qrcode_version": self.ui.tools2_defaults_form.tools2_qrcode_group.version_entry,
  1266. "tools_qrcode_error": self.ui.tools2_defaults_form.tools2_qrcode_group.error_radio,
  1267. "tools_qrcode_box_size": self.ui.tools2_defaults_form.tools2_qrcode_group.bsize_entry,
  1268. "tools_qrcode_border_size": self.ui.tools2_defaults_form.tools2_qrcode_group.border_size_entry,
  1269. "tools_qrcode_qrdata": self.ui.tools2_defaults_form.tools2_qrcode_group.text_data,
  1270. "tools_qrcode_polarity": self.ui.tools2_defaults_form.tools2_qrcode_group.pol_radio,
  1271. "tools_qrcode_rounded": self.ui.tools2_defaults_form.tools2_qrcode_group.bb_radio,
  1272. "tools_qrcode_fill_color": self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry,
  1273. "tools_qrcode_back_color": self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry,
  1274. "tools_qrcode_sel_limit": self.ui.tools2_defaults_form.tools2_qrcode_group.sel_limit_entry,
  1275. # Copper Thieving Tool
  1276. "tools_copper_thieving_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_entry,
  1277. "tools_copper_thieving_margin": self.ui.tools2_defaults_form.tools2_cfill_group.margin_entry,
  1278. "tools_copper_thieving_reference": self.ui.tools2_defaults_form.tools2_cfill_group.reference_radio,
  1279. "tools_copper_thieving_box_type": self.ui.tools2_defaults_form.tools2_cfill_group.bbox_type_radio,
  1280. "tools_copper_thieving_circle_steps": self.ui.tools2_defaults_form.tools2_cfill_group.circlesteps_entry,
  1281. "tools_copper_thieving_fill_type": self.ui.tools2_defaults_form.tools2_cfill_group.fill_type_radio,
  1282. "tools_copper_thieving_dots_dia": self.ui.tools2_defaults_form.tools2_cfill_group.dot_dia_entry,
  1283. "tools_copper_thieving_dots_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.dot_spacing_entry,
  1284. "tools_copper_thieving_squares_size": self.ui.tools2_defaults_form.tools2_cfill_group.square_size_entry,
  1285. "tools_copper_thieving_squares_spacing":
  1286. self.ui.tools2_defaults_form.tools2_cfill_group.squares_spacing_entry,
  1287. "tools_copper_thieving_lines_size": self.ui.tools2_defaults_form.tools2_cfill_group.line_size_entry,
  1288. "tools_copper_thieving_lines_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.lines_spacing_entry,
  1289. "tools_copper_thieving_rb_margin": self.ui.tools2_defaults_form.tools2_cfill_group.rb_margin_entry,
  1290. "tools_copper_thieving_rb_thickness": self.ui.tools2_defaults_form.tools2_cfill_group.rb_thickness_entry,
  1291. "tools_copper_thieving_mask_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_ppm_entry,
  1292. # Fiducials Tool
  1293. "tools_fiducials_dia": self.ui.tools2_defaults_form.tools2_fiducials_group.dia_entry,
  1294. "tools_fiducials_margin": self.ui.tools2_defaults_form.tools2_fiducials_group.margin_entry,
  1295. "tools_fiducials_mode": self.ui.tools2_defaults_form.tools2_fiducials_group.mode_radio,
  1296. "tools_fiducials_second_pos": self.ui.tools2_defaults_form.tools2_fiducials_group.pos_radio,
  1297. "tools_fiducials_type": self.ui.tools2_defaults_form.tools2_fiducials_group.fid_type_radio,
  1298. "tools_fiducials_line_thickness": self.ui.tools2_defaults_form.tools2_fiducials_group.line_thickness_entry,
  1299. # Calibration Tool
  1300. "tools_cal_calsource": self.ui.tools2_defaults_form.tools2_cal_group.cal_source_radio,
  1301. "tools_cal_travelz": self.ui.tools2_defaults_form.tools2_cal_group.travelz_entry,
  1302. "tools_cal_verz": self.ui.tools2_defaults_form.tools2_cal_group.verz_entry,
  1303. "tools_cal_zeroz": self.ui.tools2_defaults_form.tools2_cal_group.zeroz_cb,
  1304. "tools_cal_toolchangez": self.ui.tools2_defaults_form.tools2_cal_group.toolchangez_entry,
  1305. "tools_cal_toolchange_xy": self.ui.tools2_defaults_form.tools2_cal_group.toolchange_xy_entry,
  1306. "tools_cal_sec_point": self.ui.tools2_defaults_form.tools2_cal_group.second_point_radio,
  1307. # Utilities
  1308. # File associations
  1309. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  1310. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  1311. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  1312. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  1313. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  1314. }
  1315. # update the Preferences GUI elements with the values in the self.defaults
  1316. self.defaults_write_form()
  1317. # When the self.defaults dictionary changes will update the Preferences GUI forms
  1318. self.defaults.set_change_callback(self.on_defaults_dict_change)
  1319. # #############################################################################
  1320. # ############################## Data #########################################
  1321. # #############################################################################
  1322. self.recent = []
  1323. self.recent_projects = []
  1324. self.clipboard = QtWidgets.QApplication.clipboard()
  1325. self.project_filename = None
  1326. self.toggle_units_ignore = False
  1327. # #############################################################################
  1328. # ########################## LOAD POSTPROCESSORS ##############################
  1329. # #############################################################################
  1330. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  1331. # the preprocessor file
  1332. self.preprocessors = load_preprocessors(self)
  1333. # make sure that always the 'default' preprocessor is the first item in the dictionary
  1334. if 'default' in self.preprocessors.keys():
  1335. new_ppp_dict = dict()
  1336. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  1337. default_pp = self.preprocessors.pop('default')
  1338. new_ppp_dict['default'] = default_pp
  1339. # then add the rest of the keys
  1340. for name, val_class in self.preprocessors.items():
  1341. new_ppp_dict[name] = val_class
  1342. # and now put back the ordered dict with 'default' key first
  1343. self.preprocessors = new_ppp_dict
  1344. for name in list(self.preprocessors.keys()):
  1345. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  1346. if name.partition('_')[0] == 'Paste':
  1347. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  1348. continue
  1349. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1350. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  1351. if name == 'hpgl':
  1352. continue
  1353. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1354. # #############################################################################
  1355. # ########################## LOAD LANGUAGES ##################################
  1356. # #############################################################################
  1357. self.languages = fcTranslate.load_languages()
  1358. for name in sorted(self.languages.values()):
  1359. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  1360. # #############################################################################
  1361. # ############################ APPLY APP LANGUAGE #############################
  1362. # #############################################################################
  1363. ret_val = fcTranslate.apply_language('strings')
  1364. if ret_val == "no language":
  1365. self.inform.emit('[ERROR] %s' %
  1366. _("Could not find the Language files. The App strings are missing."))
  1367. log.debug("Could not find the Language files. The App strings are missing.")
  1368. else:
  1369. # make the current language the current selection on the language combobox
  1370. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1371. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1372. # #############################################################################
  1373. # ########################### CREATE UNIQUE SERIAL NUMBER #####################
  1374. # #############################################################################
  1375. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1376. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1377. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  1378. self.save_defaults(silent=True, first_time=True)
  1379. self.propagate_defaults(silent=True)
  1380. # def auto_save_defaults():
  1381. # try:
  1382. # self.save_defaults(silent=True)
  1383. # self.propagate_defaults(silent=True)
  1384. # finally:
  1385. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1386. # the following lines activates automatic defaults save
  1387. # if user_defaults:
  1388. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1389. # #############################################################################
  1390. # ########################### UPDATE THE OPTIONS ##############################
  1391. # #############################################################################
  1392. self.options = LoudDict()
  1393. # ----------------------------------------------------------------------------------------------------
  1394. # Update the self.options from the self.defaults
  1395. # The self.defaults holds the application defaults while the self.options holds the object defaults
  1396. # -----------------------------------------------------------------------------------------------------
  1397. # Copy app defaults to project options
  1398. for def_key, def_val in self.defaults.items():
  1399. self.options[def_key] = deepcopy(def_val)
  1400. # self.options.update(self.defaults)
  1401. self.gen_form = None
  1402. self.ger_form = None
  1403. self.exc_form = None
  1404. self.geo_form = None
  1405. self.cnc_form = None
  1406. self.tools_form = None
  1407. self.tools2_form = None
  1408. self.fa_form = None
  1409. # Will show the Preferences GUI
  1410. self.show_preferences_gui()
  1411. # Initialize the color box's color in Preferences -> Global -> Color
  1412. self.init_color_pickers_in_preferences_gui()
  1413. # ### End of Data ####
  1414. # #############################################################################
  1415. # ######################## SETUP OBJECT COLLECTION ############################
  1416. # #############################################################################
  1417. self.collection = ObjectCollection(self)
  1418. self.ui.project_tab_layout.addWidget(self.collection.view)
  1419. # ### Adjust tabs width ## ##
  1420. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1421. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1422. self.collection.view.setMinimumWidth(290)
  1423. self.log.debug("Finished creating Object Collection.")
  1424. # #############################################################################
  1425. # ############################## SETUP Plot Area ##############################
  1426. # #############################################################################
  1427. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1428. if self.defaults["global_graphic_engine"] == '3D':
  1429. self.is_legacy = False
  1430. else:
  1431. self.is_legacy = True
  1432. # Event signals disconnect id holders
  1433. self.mp = None
  1434. self.mm = None
  1435. self.mr = None
  1436. self.mdc = None
  1437. self.mp_zc = None
  1438. # Matplotlib axis
  1439. self.axes = None
  1440. if show_splash:
  1441. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1442. "Canvas initialization started."),
  1443. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1444. color=QtGui.QColor("gray"))
  1445. start_plot_time = time.time() # debug
  1446. self.plotcanvas = None
  1447. self.app_cursor = None
  1448. self.hover_shapes = None
  1449. # setup the PlotCanvas
  1450. self.on_plotcanvas_setup()
  1451. end_plot_time = time.time()
  1452. self.used_time = end_plot_time - start_plot_time
  1453. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1454. if show_splash:
  1455. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1456. "Canvas initialization started.\n"
  1457. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1458. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1459. color=QtGui.QColor("gray"))
  1460. self.ui.splitter.setStretchFactor(1, 2)
  1461. # #############################################################################
  1462. # ################################### SYS TRAY ################################
  1463. # #############################################################################
  1464. if self.defaults["global_systray_icon"]:
  1465. self.parent_w = QtWidgets.QWidget()
  1466. if self.cmd_line_headless == 1:
  1467. self.trayIcon = FlatCAMSystemTray(app=self,
  1468. icon=QtGui.QIcon(self.resource_location + '/flatcam_icon32_green.png'),
  1469. headless=True,
  1470. parent=self.parent_w)
  1471. else:
  1472. self.trayIcon = FlatCAMSystemTray(app=self,
  1473. icon=QtGui.QIcon(self.resource_location + '/flatcam_icon32_green.png'),
  1474. parent=self.parent_w)
  1475. # #############################################################################
  1476. # ################################## Worker SETUP #############################
  1477. # #############################################################################
  1478. if self.defaults["global_worker_number"]:
  1479. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1480. else:
  1481. self.workers = WorkerStack(workers_number=2)
  1482. self.worker_task.connect(self.workers.add_task)
  1483. self.log.debug("Finished creating Workers crew.")
  1484. # #############################################################################
  1485. # ################################# Activity Monitor ##########################
  1486. # #############################################################################
  1487. self.activity_view = FlatCAMActivityView(app=self)
  1488. self.ui.infobar.addWidget(self.activity_view)
  1489. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1490. # #############################################################################
  1491. # ################################## Signal handling ##########################
  1492. # #############################################################################
  1493. # ################################# Custom signals ###########################
  1494. # signal for displaying messages in status bar
  1495. self.inform.connect(self.info)
  1496. # signal to be called when the app is quiting
  1497. self.app_quit.connect(self.quit_application)
  1498. self.message.connect(self.message_dialog)
  1499. self.progress.connect(self.set_progress_bar)
  1500. # signals that are emitted when object state changes
  1501. self.object_created.connect(self.on_object_created)
  1502. self.object_changed.connect(self.on_object_changed)
  1503. self.object_plotted.connect(self.on_object_plotted)
  1504. self.plots_updated.connect(self.on_plots_updated)
  1505. # signals emitted when file state change
  1506. self.file_opened.connect(self.register_recent)
  1507. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1508. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1509. # ############# Standard signals ###################
  1510. # ### Menu
  1511. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1512. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1513. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1514. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1515. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  1516. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1517. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1518. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1519. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1520. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1521. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1522. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1523. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1524. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1525. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1526. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1527. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1528. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  1529. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1530. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1531. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1532. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1533. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1534. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1535. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1536. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1537. self.ui.menufilesave_object_pdf.triggered.connect(self.on_file_save_object_pdf)
  1538. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1539. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1540. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1541. self.ui.menufile_exit.triggered.connect(self.final_save)
  1542. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1543. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1544. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1545. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1546. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1547. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1548. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1549. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1550. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1551. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1552. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1553. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1554. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1555. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1556. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1557. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1558. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1559. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1560. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1561. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1562. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1563. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1564. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1565. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1566. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1567. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1568. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1569. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1570. self.ui.menuoptions_tools_db.triggered.connect(self.on_tools_database)
  1571. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1572. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1573. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1574. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1575. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1576. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1577. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1578. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1579. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1580. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1581. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1582. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  1583. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1584. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  1585. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1586. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  1587. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1588. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1589. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1590. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1591. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1592. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1593. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1594. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1595. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1596. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1597. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1598. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1599. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1600. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1601. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1602. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1603. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1604. # ToolBar signals
  1605. self.connect_toolbar_signals()
  1606. # Notebook and Plot Tab Area signals
  1607. # make the right click on the notebook tab and plot tab area tab raise a menu
  1608. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1609. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1610. self.on_tab_setup_context_menu()
  1611. # activate initial state
  1612. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1613. # Context Menu
  1614. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1615. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1616. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1617. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1618. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1619. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1620. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1621. self.ui.clearplot.triggered.connect(self.clear_plots)
  1622. self.ui.replot.triggered.connect(self.plot_all)
  1623. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1624. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1625. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1626. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1627. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1628. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1629. # Preferences Plot Area TAB
  1630. self.ui.pref_save_button.clicked.connect(lambda: self.on_save_button(save_to_file=True))
  1631. self.ui.pref_apply_button.clicked.connect(lambda: self.on_save_button(save_to_file=False))
  1632. self.ui.pref_close_button.clicked.connect(self.on_pref_close_button)
  1633. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1634. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1635. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1636. # #############################################################################
  1637. # ######################### GUI PREFERENCES SIGNALS ###########################
  1638. # #############################################################################
  1639. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  1640. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1641. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1642. )
  1643. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1644. lambda: self.on_toggle_units(no_pref=False))
  1645. # #############################################################################
  1646. # ############################# GUI COLORS SIGNALS ############################
  1647. # #############################################################################
  1648. # Setting plot colors signals
  1649. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1650. self.on_pf_color_entry)
  1651. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1652. self.on_pf_color_button)
  1653. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1654. self.on_pf_color_spinner)
  1655. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1656. self.on_pf_color_slider)
  1657. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1658. self.on_pl_color_entry)
  1659. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1660. self.on_pl_color_button)
  1661. # Setting selection (left - right) colors signals
  1662. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1663. self.on_sf_color_entry)
  1664. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1665. self.on_sf_color_button)
  1666. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1667. self.on_sf_color_spinner)
  1668. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1669. self.on_sf_color_slider)
  1670. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1671. self.on_sl_color_entry)
  1672. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1673. self.on_sl_color_button)
  1674. # Setting selection (right - left) colors signals
  1675. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1676. self.on_alt_sf_color_entry)
  1677. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1678. self.on_alt_sf_color_button)
  1679. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1680. self.on_alt_sf_color_spinner)
  1681. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1682. self.on_alt_sf_color_slider)
  1683. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1684. self.on_alt_sl_color_entry)
  1685. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1686. self.on_alt_sl_color_button)
  1687. # Setting Editor Draw colors signals
  1688. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1689. self.on_draw_color_entry)
  1690. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1691. self.on_draw_color_button)
  1692. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1693. self.on_sel_draw_color_entry)
  1694. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1695. self.on_sel_draw_color_button)
  1696. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1697. self.on_proj_color_entry)
  1698. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1699. self.on_proj_color_button)
  1700. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1701. self.on_proj_color_dis_entry)
  1702. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1703. self.on_proj_color_dis_button)
  1704. # ############################# workspace setting signals #####################
  1705. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1706. self.ui.general_defaults_form.general_gui_group.wk_orientation_radio.activated_custom.connect(
  1707. self.on_workspace_modified
  1708. )
  1709. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1710. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1711. # #############################################################################
  1712. # ############################# GUI SETTINGS SIGNALS ##########################
  1713. # #############################################################################
  1714. self.ui.general_defaults_form.general_gui_set_group.theme_radio.activated_custom.connect(self.on_theme_change)
  1715. self.ui.general_defaults_form.general_gui_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1716. # ########## CNC Job related signals #############
  1717. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1718. self.on_cnc_custom_parameters)
  1719. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1720. self.on_annotation_fontcolor_entry)
  1721. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1722. self.on_annotation_fontcolor_button)
  1723. # ########## Tools related signals #############
  1724. # Film Tool
  1725. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1726. self.on_film_color_entry)
  1727. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1728. self.on_film_color_button)
  1729. # QRCode Tool
  1730. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  1731. self.on_qrcode_fill_color_entry)
  1732. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  1733. self.on_qrcode_fill_color_button)
  1734. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  1735. self.on_qrcode_back_color_entry)
  1736. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  1737. self.on_qrcode_back_color_button)
  1738. # portability changed signal
  1739. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1740. # Object list
  1741. self.collection.view.activated.connect(self.on_row_activated)
  1742. self.collection.item_selected.connect(self.on_row_selected)
  1743. self.object_status_changed.connect(self.on_collection_updated)
  1744. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1745. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1746. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1747. # Export Excellon parameters.
  1748. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1749. self.on_update_exc_export
  1750. )
  1751. # call it once to make sure it is updated at startup
  1752. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1753. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1754. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1755. self.on_excellon_defaults_button)
  1756. # when there are arguments at application startup this get launched
  1757. self.args_at_startup[list].connect(self.on_startup_args)
  1758. # #############################################################################
  1759. # ########################## FILE ASSOCIATIONS SIGNALS ########################
  1760. # #############################################################################
  1761. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1762. lambda: self.restore_extensions(ext_type='excellon'))
  1763. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1764. lambda: self.restore_extensions(ext_type='gcode'))
  1765. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1766. lambda: self.restore_extensions(ext_type='gerber'))
  1767. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1768. lambda: self.delete_all_extensions(ext_type='excellon'))
  1769. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1770. lambda: self.delete_all_extensions(ext_type='gcode'))
  1771. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1772. lambda: self.delete_all_extensions(ext_type='gerber'))
  1773. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1774. lambda: self.add_extension(ext_type='excellon'))
  1775. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1776. lambda: self.add_extension(ext_type='gcode'))
  1777. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1778. lambda: self.add_extension(ext_type='gerber'))
  1779. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1780. lambda: self.del_extension(ext_type='excellon'))
  1781. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1782. lambda: self.del_extension(ext_type='gcode'))
  1783. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1784. lambda: self.del_extension(ext_type='gerber'))
  1785. # connect the 'Apply' buttons from the Preferences/File Associations
  1786. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1787. lambda: self.on_register_files(obj_type='excellon'))
  1788. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1789. lambda: self.on_register_files(obj_type='gcode'))
  1790. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1791. lambda: self.on_register_files(obj_type='gerber'))
  1792. # #############################################################################
  1793. # ################################ KEYWORDS SIGNALS ###########################
  1794. # #############################################################################
  1795. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1796. lambda: self.restore_extensions(ext_type='keyword'))
  1797. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1798. lambda: self.delete_all_extensions(ext_type='keyword'))
  1799. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1800. lambda: self.add_extension(ext_type='keyword'))
  1801. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1802. lambda: self.del_extension(ext_type='keyword'))
  1803. # splash screen button signal
  1804. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1805. # connect the abort_all_tasks related slots to the related signals
  1806. self.proc_container.idle_flag.connect(self.app_is_idle)
  1807. # signal emitted when a tab is closed in the Plot Area
  1808. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1809. # #####################################################################################
  1810. # ########### FINISHED CONNECTING SIGNALS #############################################
  1811. # #####################################################################################
  1812. self.log.debug("Finished connecting Signals.")
  1813. # #####################################################################################
  1814. # ########################## Other setups #############################################
  1815. # #####################################################################################
  1816. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  1817. # depending on from where those tools are called different actions can be done
  1818. self.call_source = 'app'
  1819. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1820. self.tool_tab_locked = False
  1821. # decide if to show or hide the Notebook side of the screen at startup
  1822. if self.defaults["global_project_at_startup"] is True:
  1823. self.ui.splitter.setSizes([1, 1])
  1824. else:
  1825. self.ui.splitter.setSizes([0, 1])
  1826. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1827. self.setup_obj_classes()
  1828. self.setup_component_editor()
  1829. # #####################################################################################
  1830. # ######################### Auto-complete KEYWORDS ####################################
  1831. # #####################################################################################
  1832. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1833. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1834. 'delete', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon', 'ee', 'export_exc',
  1835. 'export_gcode', 'export_gerber', 'egr', 'export_svg', 'ext', 'exteriors', 'follow',
  1836. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1837. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1838. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1839. 'mirror', 'ncc',
  1840. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1841. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  1842. 'paint', 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1843. 'save', 'save_project',
  1844. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  1845. 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1846. 'version', 'write_gcode'
  1847. ]
  1848. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1849. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1850. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'auto', 'axis',
  1851. 'axisoffset',
  1852. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1853. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1854. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1855. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1856. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1857. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1858. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1859. 'spacing_columns',
  1860. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'tooldia', 'use_threads', 'value',
  1861. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1862. ]
  1863. self.tcl_keywords = [
  1864. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1865. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1866. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1867. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1868. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1869. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1870. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1871. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1872. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1873. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1874. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1875. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1876. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1877. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1878. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1879. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1880. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1881. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1882. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1883. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1884. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1885. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1886. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1887. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1888. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1889. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1890. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1891. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1892. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1893. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1894. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1895. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1896. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1897. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1898. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1899. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1900. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1901. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1902. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1903. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1904. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1905. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1906. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1907. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1908. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1909. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1910. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1911. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1912. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1913. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1914. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1915. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1916. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1917. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1918. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1919. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1920. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1921. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1922. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1923. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1924. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1925. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1926. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1927. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1928. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1929. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1930. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1931. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1932. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1933. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1934. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1935. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1936. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1937. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1938. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1939. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1940. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1941. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1942. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1943. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1944. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1945. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1946. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1947. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1948. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1949. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1950. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1951. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1952. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1953. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1954. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1955. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1956. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1957. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1958. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1959. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1960. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1961. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1962. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1963. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1964. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1965. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1966. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1967. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1968. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1969. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1970. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1971. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1972. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1973. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1974. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1975. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1976. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1977. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1978. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1979. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1980. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1981. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1982. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1983. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1984. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1985. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1986. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1987. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1988. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1989. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1990. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1991. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1992. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1993. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1994. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1995. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1996. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1997. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1998. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1999. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  2000. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  2001. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  2002. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  2003. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  2004. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  2005. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  2006. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  2007. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  2008. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  2009. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  2010. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  2011. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  2012. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  2013. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  2014. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  2015. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  2016. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  2017. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  2018. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  2019. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  2020. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  2021. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  2022. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  2023. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  2024. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  2025. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  2026. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  2027. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  2028. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  2029. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  2030. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  2031. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  2032. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  2033. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  2034. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  2035. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  2036. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  2037. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  2038. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  2039. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  2040. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  2041. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  2042. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  2043. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  2044. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  2045. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  2046. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  2047. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  2048. ]
  2049. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  2050. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2051. # ####################################################################################
  2052. # ####################### Shell SETUP ################################################
  2053. # ####################################################################################
  2054. # this will hold the TCL instance
  2055. self.tcl = None
  2056. self.init_tcl()
  2057. self.shell = FCShell(self, version=self.version)
  2058. self.shell._edit.set_model_data(self.myKeywords)
  2059. self.shell.setWindowIcon(self.ui.app_icon)
  2060. self.shell.setWindowTitle("FlatCAM Shell")
  2061. self.shell.resize(*self.defaults["global_shell_shape"])
  2062. self.shell.append_output("FlatCAM %s - " % self.version)
  2063. self.shell.append_output(_("Type >help< to get started\n\n"))
  2064. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  2065. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  2066. self.ui.shell_dock.setWidget(self.shell)
  2067. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  2068. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  2069. QtWidgets.QDockWidget.DockWidgetFloatable |
  2070. QtWidgets.QDockWidget.DockWidgetClosable)
  2071. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  2072. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  2073. if self.defaults["global_shell_at_startup"]:
  2074. self.ui.shell_dock.show()
  2075. else:
  2076. self.ui.shell_dock.hide()
  2077. # ##################################################################################
  2078. # ###################### Tools and Plugins #########################################
  2079. # ##################################################################################
  2080. self.dblsidedtool = None
  2081. self.distance_tool = None
  2082. self.distance_min_tool = None
  2083. self.panelize_tool = None
  2084. self.film_tool = None
  2085. self.paste_tool = None
  2086. self.calculator_tool = None
  2087. self.rules_tool = None
  2088. self.sub_tool = None
  2089. self.move_tool = None
  2090. self.cutout_tool = None
  2091. self.ncclear_tool = None
  2092. self.optimal_tool = None
  2093. self.paint_tool = None
  2094. self.transform_tool = None
  2095. self.properties_tool = None
  2096. self.pdf_tool = None
  2097. self.image_tool = None
  2098. self.pcb_wizard_tool = None
  2099. self.cal_exc_tool = None
  2100. self.qrcode_tool = None
  2101. self.copper_thieving_tool = None
  2102. self.fiducial_tool = None
  2103. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2104. self.install_tools()
  2105. # ##################################################################################
  2106. # ########################### SETUP RECENT ITEMS ###################################
  2107. # ##################################################################################
  2108. self.setup_recent_items()
  2109. # ##################################################################################
  2110. # ########################### BookMarks Manager ####################################
  2111. # ##################################################################################
  2112. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  2113. self.install_bookmarks()
  2114. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  2115. # ##################################################################################
  2116. # ############################## Tools Database ####################################
  2117. # ##################################################################################
  2118. self.tools_db_tab = None
  2119. # ### System Font Parsing ###
  2120. # self.f_parse = ParseFont(self)
  2121. # self.parse_system_fonts()
  2122. # #####################################################################################
  2123. # ######################## Check for updates ##########################################
  2124. # #####################################################################################
  2125. # Separate thread (Not worker)
  2126. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2127. if (self.beta is False or self.beta is None) and \
  2128. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  2129. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2130. self.thr2 = QtCore.QThread()
  2131. self.worker_task.emit({'fcn': self.version_check,
  2132. 'params': []})
  2133. self.thr2.start(QtCore.QThread.LowPriority)
  2134. # #####################################################################################
  2135. # ######################### Register files with FlatCAM; #############################
  2136. # ######################### It works only for Windows for now ########################
  2137. # #####################################################################################
  2138. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2139. self.on_register_files()
  2140. # #####################################################################################
  2141. # ###################### Variables for global usage ###################################
  2142. # #####################################################################################
  2143. # hold the App units
  2144. self.units = 'MM'
  2145. # coordinates for relative position display
  2146. self.rel_point1 = (0, 0)
  2147. self.rel_point2 = (0, 0)
  2148. # variable to store coordinates
  2149. self.pos = (0, 0)
  2150. self.pos_canvas = (0, 0)
  2151. self.pos_jump = (0, 0)
  2152. # variable to store mouse coordinates
  2153. self.mouse = [0, 0]
  2154. # decide if we have a double click or single click
  2155. self.doubleclick = False
  2156. # store here the is_dragging value
  2157. self.event_is_dragging = False
  2158. # variable to store if a command is active (then the var is not None) and which one it is
  2159. self.command_active = None
  2160. # variable to store the status of moving selection action
  2161. # None value means that it's not an selection action
  2162. # True value = a selection from left to right
  2163. # False value = a selection from right to left
  2164. self.selection_type = None
  2165. # List to store the objects that are currently loaded in FlatCAM
  2166. # This list is updated on each object creation or object delete
  2167. self.all_objects_list = list()
  2168. # List to store the objects that are selected
  2169. self.sel_objects_list = list()
  2170. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2171. self.key_modifiers = None
  2172. # Variable to hold the status of the axis
  2173. self.toggle_axis = True
  2174. # Variable to hold the status of the grid lines
  2175. self.toggle_grid_lines = True
  2176. # Variable to store the status of the fullscreen event
  2177. self.toggle_fscreen = False
  2178. # Variable to store the status of the code editor
  2179. self.toggle_codeeditor = False
  2180. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2181. self.click_noproject = False
  2182. self.cursor = None
  2183. # Variable to store the GCODE that was edited
  2184. self.gcode_edited = ""
  2185. self.text_editor_tab = None
  2186. # reference for the self.ui.code_editor
  2187. self.reference_code_editor = None
  2188. self.script_code = ''
  2189. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2190. self.preferences_changed_flag = False
  2191. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  2192. self.tools_db_changed_flag = False
  2193. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2194. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2195. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2196. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2197. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2198. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2199. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  2200. 'sbp', 'tap', 'xpi']
  2201. self.svg_list = ['svg']
  2202. self.dxf_list = ['dxf']
  2203. self.pdf_list = ['pdf']
  2204. self.prj_list = ['flatprj']
  2205. self.conf_list = ['flatconfig']
  2206. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2207. # flag for polygons not cleared
  2208. self.poly_not_cleared = False
  2209. # VisPy visuals
  2210. self.isHovering = False
  2211. self.notHovering = True
  2212. # Window geometry
  2213. self.x_pos = None
  2214. self.y_pos = None
  2215. self.width = None
  2216. self.height = None
  2217. # when True, the app has to return from any thread
  2218. self.abort_flag = False
  2219. # set the value used in the Windows Title
  2220. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  2221. # this holds a widget that is installed in the Plot Area when View Source option is used
  2222. self.source_editor_tab = None
  2223. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  2224. # VisPy visuals
  2225. if self.is_legacy is False:
  2226. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  2227. else:
  2228. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  2229. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  2230. # ###############################################################################
  2231. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2232. # ############# It's done only once after install ###############
  2233. # ###############################################################################
  2234. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2235. fac_def_from_file = factory_file.read()
  2236. factory_defaults = json.loads(fac_def_from_file)
  2237. # if the file contain an empty dictionary then save the factory defaults into the file
  2238. if self.defaults["first_run"] is True:
  2239. self.save_factory_defaults(silent_message=False)
  2240. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2241. initial_lay = 'compact'
  2242. self.on_layout(lay=initial_lay)
  2243. # Set the combobox in Preferences to the current layout
  2244. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2245. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2246. factory_file.close()
  2247. # and then make the factory_defaults.FlatConfig file read_only so it can't be modified after creation.
  2248. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2249. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2250. # after the first run, this object should be False
  2251. self.defaults["first_run"] = False
  2252. # ###############################################################################
  2253. # ################# ADDING FlatCAM EDITORS section ##############################
  2254. # ###############################################################################
  2255. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2256. # at the first launch of the App , the editors will not be functional.
  2257. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2258. self.exc_editor = FlatCAMExcEditor(self)
  2259. self.grb_editor = FlatCAMGrbEditor(self)
  2260. self.log.debug("Finished adding FlatCAM Editor's.")
  2261. self.set_ui_title(name=_("New Project - Not saved"))
  2262. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2263. current_platform = platform.architecture()[0]
  2264. if current_platform != '64bit':
  2265. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2266. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2267. # ###############################################################################
  2268. # ####################### Finished the CONSTRUCTOR ##############################
  2269. # ###############################################################################
  2270. App.log.debug("END of constructor. Releasing control.")
  2271. # #####################################################################################
  2272. # ########################## SHOW GUI #################################################
  2273. # #####################################################################################
  2274. # if the app is not started as headless, show it
  2275. if self.cmd_line_headless != 1:
  2276. if show_splash:
  2277. # finish the splash
  2278. self.splash.finish(self.ui)
  2279. mgui_settings = QSettings("Open Source", "FlatCAM")
  2280. if mgui_settings.contains("maximized_gui"):
  2281. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  2282. if maximized_ui is True:
  2283. self.ui.showMaximized()
  2284. else:
  2285. self.ui.show()
  2286. else:
  2287. self.ui.show()
  2288. if self.defaults["global_systray_icon"]:
  2289. self.trayIcon.show()
  2290. else:
  2291. log.warning("******************* RUNNING HEADLESS *******************")
  2292. # #####################################################################################
  2293. # ########################## START-UP ARGUMENTS #######################################
  2294. # #####################################################################################
  2295. # test if the program was started with a script as parameter
  2296. if self.cmd_line_shellvar:
  2297. try:
  2298. cnt = 0
  2299. command_tcl = 0
  2300. for i in self.cmd_line_shellvar.split(','):
  2301. if i is not None:
  2302. # noinspection PyBroadException
  2303. try:
  2304. command_tcl = eval(i)
  2305. except Exception:
  2306. command_tcl = i
  2307. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2308. cnt += 1
  2309. # if there are Windows paths then replace the path separator with a Unix like one
  2310. if sys.platform == 'win32':
  2311. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2312. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2313. except Exception as ext:
  2314. print("ERROR: ", ext)
  2315. sys.exit(2)
  2316. if self.cmd_line_shellfile:
  2317. try:
  2318. if self.ui.shell_dock.isHidden():
  2319. self.ui.shell_dock.show()
  2320. with open(self.cmd_line_shellfile, "r") as myfile:
  2321. if show_splash:
  2322. self.splash.showMessage('%s: %ssec\n%s' % (
  2323. _("Canvas initialization started.\n"
  2324. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2325. _("Executing Tcl Script ...")),
  2326. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2327. color=QtGui.QColor("gray"))
  2328. cmd_line_shellfile_text = myfile.read()
  2329. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2330. except Exception as ext:
  2331. print("ERROR: ", ext)
  2332. sys.exit(2)
  2333. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2334. # the path/file_name must be enclosed in quotes if it contain spaces
  2335. if App.args:
  2336. self.args_at_startup.emit(App.args)
  2337. if self.old_defaults_found is True:
  2338. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  2339. "Please reboot the application to update."))
  2340. self.old_defaults_found = False
  2341. @staticmethod
  2342. def copy_and_overwrite(from_path, to_path):
  2343. """
  2344. From here:
  2345. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2346. :param from_path: source path
  2347. :param to_path: destination path
  2348. :return: None
  2349. """
  2350. if os.path.exists(to_path):
  2351. shutil.rmtree(to_path)
  2352. try:
  2353. shutil.copytree(from_path, to_path)
  2354. except FileNotFoundError:
  2355. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2356. shutil.copytree(from_new_path, to_path)
  2357. def on_startup_args(self, args, silent=False):
  2358. """
  2359. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2360. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  2361. :param args: a list containing the application args at startup
  2362. :return: None
  2363. """
  2364. if args is not None:
  2365. args_to_process = args
  2366. else:
  2367. args_to_process = App.args
  2368. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2369. for argument in args_to_process:
  2370. if '.FlatPrj'.lower() in argument.lower():
  2371. try:
  2372. project_name = str(argument)
  2373. if project_name == "":
  2374. if silent is False:
  2375. self.inform.emit(_("Open cancelled."))
  2376. else:
  2377. # self.open_project(project_name)
  2378. run_from_arg = True
  2379. # self.worker_task.emit({'fcn': self.open_project,
  2380. # 'params': [project_name, run_from_arg]})
  2381. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2382. except Exception as e:
  2383. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2384. elif '.FlatConfig'.lower() in argument.lower():
  2385. try:
  2386. file_name = str(argument)
  2387. if file_name == "":
  2388. if silent is False:
  2389. self.inform.emit(_("Open Config file failed."))
  2390. else:
  2391. run_from_arg = True
  2392. # self.worker_task.emit({'fcn': self.open_config_file,
  2393. # 'params': [file_name, run_from_arg]})
  2394. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2395. except Exception as e:
  2396. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2397. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2398. try:
  2399. file_name = str(argument)
  2400. if file_name == "":
  2401. if silent is False:
  2402. self.inform.emit(_("Open Script file failed."))
  2403. else:
  2404. if silent is False:
  2405. self.on_fileopenscript(name=file_name)
  2406. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2407. self.on_filerunscript(name=file_name)
  2408. except Exception as e:
  2409. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2410. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2411. log.debug("App.on_startup_args() --> Quit event.")
  2412. sys.exit()
  2413. elif 'save'.lower() in argument.lower():
  2414. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2415. self.save_defaults()
  2416. else:
  2417. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2418. proc_arg = argument.lower()
  2419. for ext in exc_list:
  2420. proc_ext = ext.replace(' ', '')
  2421. proc_ext = '.%s' % proc_ext
  2422. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2423. file_name = str(argument)
  2424. if file_name == "":
  2425. if silent is False:
  2426. self.inform.emit(_("Open Excellon file failed."))
  2427. else:
  2428. self.on_fileopenexcellon(name=file_name)
  2429. return
  2430. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2431. for ext in gco_list:
  2432. proc_ext = ext.replace(' ', '')
  2433. proc_ext = '.%s' % proc_ext
  2434. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2435. file_name = str(argument)
  2436. if file_name == "":
  2437. if silent is False:
  2438. self.inform.emit(_("Open GCode file failed."))
  2439. else:
  2440. self.on_fileopengcode(name=file_name)
  2441. return
  2442. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2443. for ext in grb_list:
  2444. proc_ext = ext.replace(' ', '')
  2445. proc_ext = '.%s' % proc_ext
  2446. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2447. file_name = str(argument)
  2448. if file_name == "":
  2449. if silent is False:
  2450. self.inform.emit(_("Open Gerber file failed."))
  2451. else:
  2452. self.on_fileopengerber(name=file_name)
  2453. return
  2454. # if it reached here without already returning then the app was registered with a file that it does not
  2455. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2456. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2457. # for arg in args_to_process:
  2458. # if 'FlatCAM.exe' in arg:
  2459. # continue
  2460. # else:
  2461. # sys.exit(2)
  2462. def set_ui_title(self, name):
  2463. """
  2464. Sets the title of the main window.
  2465. :param name: String that store the project path and project name
  2466. :return: None
  2467. """
  2468. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2469. (self.version,
  2470. ('BETA' if self.beta else ''),
  2471. platform.architecture()[0],
  2472. self.engine,
  2473. name)
  2474. )
  2475. def on_theme_change(self, val):
  2476. t_settings = QSettings("Open Source", "FlatCAM")
  2477. t_settings.setValue('theme', val)
  2478. # This will write the setting to the platform specific storage.
  2479. del t_settings
  2480. self.on_app_restart()
  2481. def on_app_restart(self):
  2482. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  2483. # be left in the SySTray
  2484. try:
  2485. self.trayIcon.hide()
  2486. except Exception:
  2487. pass
  2488. fcTranslate.restart_program(app=self)
  2489. def defaults_read_form(self):
  2490. """
  2491. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2492. :return: None
  2493. """
  2494. for option in self.defaults_form_fields:
  2495. try:
  2496. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2497. except Exception as e:
  2498. log.debug("App.defaults_read_form() --> %s" % str(e))
  2499. def defaults_write_form(self, factor=None, fl_units=None):
  2500. """
  2501. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2502. self.defaults dictionary.
  2503. :param factor: will apply a factor to the values that written in the GUI elements
  2504. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2505. :return: None
  2506. """
  2507. for option in self.defaults:
  2508. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2509. # try:
  2510. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2511. # except KeyError:
  2512. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2513. # # TODO: Rethink this?
  2514. # pass
  2515. def defaults_write_form_field(self, field, factor=None, units=None):
  2516. """
  2517. Basically it is the worker in the self.defaults_write_form()
  2518. :param field: the GUI element in Preferences GUI to be updated
  2519. :param factor: factor to be applied to the field parameter
  2520. :param units: current FLatCAM measuring units
  2521. :return: None, it updates GUI elements
  2522. """
  2523. try:
  2524. if factor is None:
  2525. if units is None:
  2526. self.defaults_form_fields[field].set_value(self.defaults[field])
  2527. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2528. self.defaults_form_fields[field].set_value(self.defaults[field])
  2529. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2530. self.defaults_form_fields[field].set_value(self.defaults[field])
  2531. else:
  2532. if units is None:
  2533. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2534. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2535. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2536. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2537. self.defaults_form_fields[field].set_value((self.defaults[field] * factor))
  2538. except KeyError:
  2539. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2540. # TODO: Rethink this?
  2541. pass
  2542. except AttributeError:
  2543. log.debug(field)
  2544. def clear_pool(self):
  2545. """
  2546. Clear the multiprocessing pool and calls garbage collector.
  2547. :return: None
  2548. """
  2549. self.pool.close()
  2550. self.pool = Pool()
  2551. self.pool_recreated.emit(self.pool)
  2552. gc.collect()
  2553. def install_tools(self):
  2554. """
  2555. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2556. Instantiation of the Tools classes.
  2557. The order that the tools are installed is important as they can depend on each other install position.
  2558. :return: None
  2559. """
  2560. self.dblsidedtool = DblSidedTool(self)
  2561. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=True)
  2562. self.cal_exc_tool = ToolCalibration(self)
  2563. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  2564. before=self.dblsidedtool.menuAction,
  2565. separator=False)
  2566. self.distance_tool = Distance(self)
  2567. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  2568. before=self.ui.menueditorigin,
  2569. separator=False)
  2570. self.distance_min_tool = DistanceMin(self)
  2571. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  2572. pos=self.ui.menuedit,
  2573. before=self.ui.menueditorigin,
  2574. separator=True)
  2575. self.panelize_tool = Panelize(self)
  2576. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  2577. self.film_tool = Film(self)
  2578. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  2579. self.paste_tool = SolderPaste(self)
  2580. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  2581. self.calculator_tool = ToolCalculator(self)
  2582. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  2583. self.sub_tool = ToolSub(self)
  2584. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  2585. pos=self.ui.menutool, separator=True)
  2586. self.rules_tool = RulesCheck(self)
  2587. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  2588. pos=self.ui.menutool, separator=False)
  2589. self.optimal_tool = ToolOptimal(self)
  2590. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  2591. pos=self.ui.menutool, separator=True)
  2592. self.move_tool = ToolMove(self)
  2593. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  2594. before=self.ui.menueditorigin, separator=True)
  2595. self.cutout_tool = CutOut(self)
  2596. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  2597. before=self.sub_tool.menuAction)
  2598. self.ncclear_tool = NonCopperClear(self)
  2599. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  2600. before=self.sub_tool.menuAction, separator=True)
  2601. self.paint_tool = ToolPaint(self)
  2602. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  2603. before=self.sub_tool.menuAction, separator=True)
  2604. self.copper_thieving_tool = ToolCopperThieving(self)
  2605. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  2606. pos=self.ui.menutool)
  2607. self.fiducial_tool = ToolFiducials(self)
  2608. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  2609. pos=self.ui.menutool)
  2610. self.qrcode_tool = QRCode(self)
  2611. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  2612. pos=self.ui.menutool)
  2613. self.transform_tool = ToolTransform(self)
  2614. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  2615. pos=self.ui.menuoptions, separator=True)
  2616. self.properties_tool = Properties(self)
  2617. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  2618. pos=self.ui.menuoptions)
  2619. self.pdf_tool = ToolPDF(self)
  2620. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  2621. pos=self.ui.menufileimport,
  2622. separator=True)
  2623. self.image_tool = ToolImage(self)
  2624. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  2625. pos=self.ui.menufileimport,
  2626. separator=True)
  2627. self.pcb_wizard_tool = PcbWizard(self)
  2628. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  2629. pos=self.ui.menufileimport)
  2630. self.log.debug("Tools are installed.")
  2631. def remove_tools(self):
  2632. """
  2633. Will remove all the actions in the Tool menu.
  2634. :return: None
  2635. """
  2636. for act in self.ui.menutool.actions():
  2637. self.ui.menutool.removeAction(act)
  2638. def init_tools(self):
  2639. """
  2640. Initialize the Tool tab in the notebook side of the central widget.
  2641. Remove the actions in the Tools menu.
  2642. Instantiate again the FlatCAM tools (plugins).
  2643. All this is required when changing the layout: standard, compact etc.
  2644. :return: None
  2645. """
  2646. log.debug("init_tools()")
  2647. # delete the data currently in the Tools Tab and the Tab itself
  2648. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2649. if widget is not None:
  2650. widget.deleteLater()
  2651. self.ui.notebook.removeTab(2)
  2652. # rebuild the Tools Tab
  2653. self.ui.tool_tab = QtWidgets.QWidget()
  2654. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2655. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2656. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2657. self.ui.tool_scroll_area = VerticalScrollArea()
  2658. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2659. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2660. # first remove all of them
  2661. self.remove_tools()
  2662. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2663. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  2664. '&Command Line\tS')
  2665. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2666. # third install all of them
  2667. self.install_tools()
  2668. self.log.debug("Tools are initialized.")
  2669. # def parse_system_fonts(self):
  2670. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2671. # 'params': []})
  2672. def connect_toolbar_signals(self):
  2673. """
  2674. Reconnect the signals to the actions in the toolbar.
  2675. This has to be done each time after the FlatCAM tools are removed/installed.
  2676. :return: None
  2677. """
  2678. # Toolbar
  2679. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2680. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2681. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2682. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2683. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2684. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2685. self.ui.replot_btn.triggered.connect(self.plot_all)
  2686. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2687. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2688. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2689. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2690. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2691. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2692. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2693. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2694. self.ui.copy_btn.triggered.connect(self.on_copy_object)
  2695. self.ui.delete_btn.triggered.connect(self.on_delete)
  2696. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  2697. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  2698. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  2699. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  2700. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2701. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2702. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2703. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2704. # Tools Toolbar Signals
  2705. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2706. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  2707. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2708. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2709. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2710. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2711. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2712. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2713. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2714. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  2715. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  2716. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2717. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2718. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  2719. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  2720. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  2721. def object2editor(self):
  2722. """
  2723. Send the current Geometry or Excellon object (if any) into the it's editor.
  2724. :return: None
  2725. """
  2726. self.report_usage("object2editor()")
  2727. # disable the objects menu as it may interfere with the Editors
  2728. self.ui.menuobjects.setDisabled(True)
  2729. edited_object = self.collection.get_active()
  2730. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2731. isinstance(edited_object, FlatCAMExcellon):
  2732. pass
  2733. else:
  2734. self.inform.emit('[WARNING_NOTCL] %s' %
  2735. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2736. return
  2737. if isinstance(edited_object, FlatCAMGeometry):
  2738. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2739. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2740. # we set the notebook to hidden
  2741. self.ui.splitter.setSizes([0, 1])
  2742. if edited_object.multigeo is True:
  2743. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  2744. if len(sel_rows) > 1:
  2745. self.inform.emit('[WARNING_NOTCL] %s' %
  2746. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  2747. "is not possible.\n"
  2748. "Edit only one geometry at a time."))
  2749. # determine the tool dia of the selected tool
  2750. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  2751. # now find the key in the edited_object.tools that has this tooldia
  2752. multi_tool = 1
  2753. for tool in edited_object.tools:
  2754. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2755. multi_tool = tool
  2756. break
  2757. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2758. else:
  2759. self.geo_editor.edit_fcgeometry(edited_object)
  2760. # set call source to the Editor we go into
  2761. self.call_source = 'geo_editor'
  2762. elif isinstance(edited_object, FlatCAMExcellon):
  2763. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2764. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2765. if self.ui.splitter.sizes()[0] == 0:
  2766. self.ui.splitter.setSizes([1, 1])
  2767. self.exc_editor.edit_fcexcellon(edited_object)
  2768. # set call source to the Editor we go into
  2769. self.call_source = 'exc_editor'
  2770. elif isinstance(edited_object, FlatCAMGerber):
  2771. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2772. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2773. if self.ui.splitter.sizes()[0] == 0:
  2774. self.ui.splitter.setSizes([1, 1])
  2775. self.grb_editor.edit_fcgerber(edited_object)
  2776. # set call source to the Editor we go into
  2777. self.call_source = 'grb_editor'
  2778. # make sure that we can't select another object while in Editor Mode:
  2779. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2780. self.ui.project_frame.setDisabled(True)
  2781. # delete any selection shape that might be active as they are not relevant in Editor
  2782. self.delete_selection_shape()
  2783. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2784. self.ui.plot_tab_area.protectTab(0)
  2785. self.inform.emit('[WARNING_NOTCL] %s' %
  2786. _("Editor is activated ..."))
  2787. self.should_we_save = True
  2788. def editor2object(self, cleanup=None):
  2789. """
  2790. Transfers the Geometry or Excellon from it's editor to the current object.
  2791. :return: None
  2792. """
  2793. self.report_usage("editor2object()")
  2794. # re-enable the objects menu that was disabled on entry in Editor mode
  2795. self.ui.menuobjects.setDisabled(False)
  2796. # do not update a geometry or excellon object unless it comes out of an editor
  2797. if self.call_source != 'app':
  2798. edited_obj = self.collection.get_active()
  2799. if cleanup is None:
  2800. msgbox = QtWidgets.QMessageBox()
  2801. msgbox.setText(_("Do you want to save the edited object?"))
  2802. msgbox.setWindowTitle(_("Close Editor"))
  2803. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2804. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2805. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2806. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2807. msgbox.setDefaultButton(bt_yes)
  2808. msgbox.exec_()
  2809. response = msgbox.clickedButton()
  2810. if response == bt_yes:
  2811. # clean the Tools Tab
  2812. self.ui.tool_scroll_area.takeWidget()
  2813. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2814. self.ui.notebook.setTabText(2, "Tool")
  2815. if isinstance(edited_obj, FlatCAMGeometry):
  2816. obj_type = "Geometry"
  2817. if cleanup is None:
  2818. self.geo_editor.update_fcgeometry(edited_obj)
  2819. self.geo_editor.update_options(edited_obj)
  2820. self.geo_editor.deactivate()
  2821. # update the geo object options so it is including the bounding box values
  2822. try:
  2823. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2824. edited_obj.options['xmin'] = xmin
  2825. edited_obj.options['ymin'] = ymin
  2826. edited_obj.options['xmax'] = xmax
  2827. edited_obj.options['ymax'] = ymax
  2828. except AttributeError as e:
  2829. self.inform.emit('[WARNING] %s' %
  2830. _("Object empty after edit."))
  2831. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2832. elif isinstance(edited_obj, FlatCAMGerber):
  2833. obj_type = "Gerber"
  2834. if cleanup is None:
  2835. self.grb_editor.update_fcgerber()
  2836. self.grb_editor.update_options(edited_obj)
  2837. self.grb_editor.deactivate_grb_editor()
  2838. # delete the old object (the source object) if it was an empty one
  2839. try:
  2840. if len(edited_obj.solid_geometry) == 0:
  2841. old_name = edited_obj.options['name']
  2842. self.collection.set_active(old_name)
  2843. self.collection.delete_active()
  2844. except TypeError:
  2845. # if the solid_geometry is a single Polygon the len() will not work
  2846. # in any case, falling here means that we have something in the solid_geometry, even if only
  2847. # a single Polygon, therefore we pass this
  2848. pass
  2849. # restore GUI to the Selected TAB
  2850. # Remove anything else in the GUI
  2851. self.ui.selected_scroll_area.takeWidget()
  2852. # Switch notebook to Selected page
  2853. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2854. elif isinstance(edited_obj, FlatCAMExcellon):
  2855. obj_type = "Excellon"
  2856. if cleanup is None:
  2857. self.exc_editor.update_fcexcellon(edited_obj)
  2858. self.exc_editor.update_options(edited_obj)
  2859. self.exc_editor.deactivate()
  2860. # delete the old object (the source object) if it was an empty one
  2861. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2862. old_name = edited_obj.options['name']
  2863. self.collection.set_active(old_name)
  2864. self.collection.delete_active()
  2865. # restore GUI to the Selected TAB
  2866. # Remove anything else in the GUI
  2867. self.ui.tool_scroll_area.takeWidget()
  2868. # Switch notebook to Selected page
  2869. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2870. else:
  2871. self.inform.emit('[WARNING_NOTCL] %s' %
  2872. _("Select a Gerber, Geometry or Excellon Object to update."))
  2873. return
  2874. self.inform.emit('[selected] %s %s' %
  2875. (obj_type, _("is updated, returning to App...")))
  2876. elif response == bt_no:
  2877. # clean the Tools Tab
  2878. self.ui.tool_scroll_area.takeWidget()
  2879. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2880. self.ui.notebook.setTabText(2, "Tool")
  2881. if isinstance(edited_obj, FlatCAMGeometry):
  2882. self.geo_editor.deactivate()
  2883. elif isinstance(edited_obj, FlatCAMGerber):
  2884. self.grb_editor.deactivate_grb_editor()
  2885. elif isinstance(edited_obj, FlatCAMExcellon):
  2886. self.exc_editor.deactivate()
  2887. # set focus on the project tab
  2888. else:
  2889. self.inform.emit('[WARNING_NOTCL] %s' %
  2890. _("Select a Gerber, Geometry or Excellon Object to update."))
  2891. return
  2892. edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  2893. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2894. elif response == bt_cancel:
  2895. return
  2896. else:
  2897. if isinstance(edited_obj, FlatCAMGeometry):
  2898. self.geo_editor.deactivate()
  2899. elif isinstance(edited_obj, FlatCAMGerber):
  2900. self.grb_editor.deactivate_grb_editor()
  2901. elif isinstance(edited_obj, FlatCAMExcellon):
  2902. self.exc_editor.deactivate()
  2903. else:
  2904. self.inform.emit('[WARNING_NOTCL] %s' %
  2905. _("Select a Gerber, Geometry or Excellon Object to update."))
  2906. return
  2907. # if notebook is hidden we show it
  2908. if self.ui.splitter.sizes()[0] == 0:
  2909. self.ui.splitter.setSizes([1, 1])
  2910. # restore the call_source to app
  2911. self.call_source = 'app'
  2912. edited_obj.plot()
  2913. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2914. self.ui.plot_tab_area.protectTab(0)
  2915. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2916. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2917. self.ui.project_frame.setDisabled(False)
  2918. def get_last_folder(self):
  2919. """
  2920. Get the folder path from where the last file was opened.
  2921. :return: String, last opened folder path
  2922. """
  2923. return self.defaults["global_last_folder"]
  2924. def get_last_save_folder(self):
  2925. """
  2926. Get the folder path from where the last file was saved.
  2927. :return: String, last saved folder path
  2928. """
  2929. loc = self.defaults["global_last_save_folder"]
  2930. if loc is None:
  2931. loc = self.defaults["global_last_folder"]
  2932. if loc is None:
  2933. loc = os.path.dirname(__file__)
  2934. return loc
  2935. def report_usage(self, resource):
  2936. """
  2937. Increments usage counter for the given resource
  2938. in self.defaults['global_stats'].
  2939. :param resource: Name of the resource.
  2940. :return: None
  2941. """
  2942. if resource in self.defaults['global_stats']:
  2943. self.defaults['global_stats'][resource] += 1
  2944. else:
  2945. self.defaults['global_stats'][resource] = 1
  2946. def init_tcl(self):
  2947. """
  2948. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2949. :return: None
  2950. """
  2951. if hasattr(self, 'tcl') and self.tcl is not None:
  2952. # self.tcl = None
  2953. # TODO we need to clean non default variables and procedures here
  2954. # new object cannot be used here as it will not remember values created for next passes,
  2955. # because tcl was execudted in old instance of TCL
  2956. pass
  2957. else:
  2958. self.tcl = tk.Tcl()
  2959. self.setup_shell()
  2960. self.log.debug("TCL Shell has been initialized.")
  2961. # TODO: This shouldn't be here.
  2962. class TclErrorException(Exception):
  2963. """
  2964. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2965. """
  2966. pass
  2967. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2968. """
  2969. Shows a message on the FlatCAM Shell
  2970. :param msg: Message to display.
  2971. :param show: Opens the shell.
  2972. :param error: Shows the message as an error.
  2973. :param warning: Shows the message as an warning.
  2974. :param success: Shows the message as an success.
  2975. :param selected: Indicate that something was selected on canvas
  2976. :return: None
  2977. """
  2978. if show:
  2979. self.ui.shell_dock.show()
  2980. try:
  2981. if error:
  2982. self.shell.append_error(msg + "\n")
  2983. elif warning:
  2984. self.shell.append_warning(msg + "\n")
  2985. elif success:
  2986. self.shell.append_success(msg + "\n")
  2987. elif selected:
  2988. self.shell.append_selected(msg + "\n")
  2989. else:
  2990. self.shell.append_output(msg + "\n")
  2991. except AttributeError:
  2992. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2993. def raise_tcl_unknown_error(self, unknownException):
  2994. """
  2995. Raise exception if is different type than TclErrorException
  2996. this is here mainly to show unknown errors inside TCL shell console.
  2997. :param unknownException:
  2998. :return:
  2999. """
  3000. if not isinstance(unknownException, self.TclErrorException):
  3001. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  3002. else:
  3003. raise unknownException
  3004. def display_tcl_error(self, error, error_info=None):
  3005. """
  3006. Escape bracket [ with '\' otherwise there is error
  3007. "ERROR: missing close-bracket" instead of real error
  3008. :param error: it may be text or exception
  3009. :param error_info: Some informations about the error
  3010. :return: None
  3011. """
  3012. if isinstance(error, Exception):
  3013. exc_type, exc_value, exc_traceback = error_info
  3014. if not isinstance(error, self.TclErrorException):
  3015. show_trace = 1
  3016. else:
  3017. show_trace = int(self.defaults['global_verbose_error_level'])
  3018. if show_trace > 0:
  3019. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  3020. trc_formated = []
  3021. for a in reversed(trc):
  3022. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  3023. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  3024. else:
  3025. text = "%s" % error
  3026. else:
  3027. text = error
  3028. text = text.replace('[', '\\[').replace('"', '\\"')
  3029. self.tcl.eval('return -code error "%s"' % text)
  3030. def raise_tcl_error(self, text):
  3031. """
  3032. This method pass exception from python into TCL as error, so we get stacktrace and reason
  3033. :param text: text of error
  3034. :return: raise exception
  3035. """
  3036. self.display_tcl_error(text)
  3037. raise self.TclErrorException(text)
  3038. def exec_command(self, text, no_echo=False):
  3039. """
  3040. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  3041. Also handles execution in separated threads
  3042. :param text: FlatCAM TclCommand with parameters
  3043. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  3044. will create crashes of the _Expandable_Edit widget
  3045. :return: output if there was any
  3046. """
  3047. self.report_usage('exec_command')
  3048. result = self.exec_command_test(text, False, no_echo=no_echo)
  3049. # MS: added this method call so the geometry is updated once the TCL command is executed
  3050. # if no_plot is None:
  3051. # self.plot_all()
  3052. return result
  3053. def exec_command_test(self, text, reraise=True, no_echo=False):
  3054. """
  3055. Same as exec_command(...) with additional control over exceptions.
  3056. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  3057. :param text: Input command
  3058. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  3059. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  3060. will create crashes of the _Expandable_Edit widget
  3061. :return: Output from the command
  3062. """
  3063. tcl_command_string = str(text)
  3064. try:
  3065. if no_echo is False:
  3066. self.shell.open_proccessing() # Disables input box.
  3067. result = self.tcl.eval(str(tcl_command_string))
  3068. if result != 'None' and no_echo is False:
  3069. self.shell.append_output(result + '\n')
  3070. except tk.TclError as e:
  3071. # This will display more precise answer if something in TCL shell fails
  3072. result = self.tcl.eval("set errorInfo")
  3073. self.log.error("Exec command Exception: %s" % (result + '\n'))
  3074. if no_echo is False:
  3075. self.shell.append_error('ERROR: ' + result + '\n')
  3076. # Show error in console and just return or in test raise exception
  3077. if reraise:
  3078. raise e
  3079. finally:
  3080. if no_echo is False:
  3081. self.shell.close_proccessing()
  3082. pass
  3083. return result
  3084. # """
  3085. # Code below is unsused. Saved for later.
  3086. # """
  3087. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  3088. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  3089. # self.log.debug(parts)
  3090. # try:
  3091. # if parts[0] not in commands:
  3092. # self.shell.append_error("Unknown command\n")
  3093. # return
  3094. #
  3095. # #import inspect
  3096. # #inspect.getargspec(someMethod)
  3097. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  3098. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  3099. # self.shell.append_error(
  3100. # "Command %s takes %d arguments. %d given.\n" %
  3101. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  3102. # )
  3103. # return
  3104. #
  3105. # cmdfcn = commands[parts[0]]["fcn"]
  3106. # cmdconv = commands[parts[0]]["converters"]
  3107. # if len(parts) - 1 > 0:
  3108. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  3109. # else:
  3110. # retval = cmdfcn()
  3111. # retfcn = commands[parts[0]]["retfcn"]
  3112. # if retval and retfcn(retval):
  3113. # self.shell.append_output(retfcn(retval) + "\n")
  3114. #
  3115. # except Exception as e:
  3116. # #self.shell.append_error(''.join(traceback.format_exc()))
  3117. # #self.shell.append_error("?\n")
  3118. # self.shell.append_error(str(e) + "\n")
  3119. def info(self, msg):
  3120. """
  3121. Informs the user. Normally on the status bar, optionally
  3122. also on the shell.
  3123. :param msg: Text to write.
  3124. :return: None
  3125. """
  3126. # Type of message in brackets at the beginning of the message.
  3127. match = re.search("\[([^\]]+)\](.*)", msg)
  3128. if match:
  3129. level = match.group(1)
  3130. msg_ = match.group(2)
  3131. self.ui.fcinfo.set_status(str(msg_), level=level)
  3132. if level.lower() == "error":
  3133. self.shell_message(msg, error=True, show=True)
  3134. elif level.lower() == "warning":
  3135. self.shell_message(msg, warning=True, show=True)
  3136. elif level.lower() == "error_notcl":
  3137. self.shell_message(msg, error=True, show=False)
  3138. elif level.lower() == "warning_notcl":
  3139. self.shell_message(msg, warning=True, show=False)
  3140. elif level.lower() == "success":
  3141. self.shell_message(msg, success=True, show=False)
  3142. elif level.lower() == "selected":
  3143. self.shell_message(msg, selected=True, show=False)
  3144. else:
  3145. self.shell_message(msg, show=False)
  3146. else:
  3147. self.ui.fcinfo.set_status(str(msg), level="info")
  3148. # make sure that if the message is to clear the infobar with a space
  3149. # is not printed over and over on the shell
  3150. if msg != '':
  3151. self.shell_message(msg)
  3152. def restore_toolbar_view(self):
  3153. """
  3154. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  3155. was saved in the defaults dictionary.
  3156. :return: None
  3157. """
  3158. tb = self.defaults["global_toolbar_view"]
  3159. if tb & 1:
  3160. self.ui.toolbarfile.setVisible(True)
  3161. else:
  3162. self.ui.toolbarfile.setVisible(False)
  3163. if tb & 2:
  3164. self.ui.toolbargeo.setVisible(True)
  3165. else:
  3166. self.ui.toolbargeo.setVisible(False)
  3167. if tb & 4:
  3168. self.ui.toolbarview.setVisible(True)
  3169. else:
  3170. self.ui.toolbarview.setVisible(False)
  3171. if tb & 8:
  3172. self.ui.toolbartools.setVisible(True)
  3173. else:
  3174. self.ui.toolbartools.setVisible(False)
  3175. if tb & 16:
  3176. self.ui.exc_edit_toolbar.setVisible(True)
  3177. else:
  3178. self.ui.exc_edit_toolbar.setVisible(False)
  3179. if tb & 32:
  3180. self.ui.geo_edit_toolbar.setVisible(True)
  3181. else:
  3182. self.ui.geo_edit_toolbar.setVisible(False)
  3183. if tb & 64:
  3184. self.ui.grb_edit_toolbar.setVisible(True)
  3185. else:
  3186. self.ui.grb_edit_toolbar.setVisible(False)
  3187. if tb & 128:
  3188. self.ui.snap_toolbar.setVisible(True)
  3189. else:
  3190. self.ui.snap_toolbar.setVisible(False)
  3191. if tb & 256:
  3192. self.ui.toolbarshell.setVisible(True)
  3193. else:
  3194. self.ui.toolbarshell.setVisible(False)
  3195. def load_defaults(self, filename):
  3196. """
  3197. Loads the aplication's default settings from current_defaults.FlatConfig into
  3198. ``self.defaults``.
  3199. :return: None
  3200. """
  3201. try:
  3202. f = open(self.data_path + "/" + filename + ".FlatConfig")
  3203. options = f.read()
  3204. f.close()
  3205. except IOError:
  3206. self.log.error("Could not load defaults file.")
  3207. self.inform.emit('[ERROR] %s' % _("Could not load defaults file."))
  3208. # in case the defaults file can't be loaded, show all toolbars
  3209. self.defaults["global_toolbar_view"] = 511
  3210. return
  3211. try:
  3212. defaults = json.loads(options)
  3213. except Exception:
  3214. # in case the defaults file can't be loaded, show all toolbars
  3215. self.defaults["global_toolbar_view"] = 511
  3216. e = sys.exc_info()[0]
  3217. App.log.error(str(e))
  3218. self.inform.emit('[ERROR] %s' % _("Failed to parse defaults file."))
  3219. return
  3220. if 'version' not in defaults or defaults['version'] != self.defaults['version']:
  3221. for k, v in defaults.items():
  3222. if k in self.defaults:
  3223. self.defaults[k] = v
  3224. # delete old factory defaults
  3225. try:
  3226. fact_def_file_path = os.path.join(self.data_path, 'factory_defaults.FlatConfig')
  3227. os.chmod(fact_def_file_path, stat.S_IRWXO | stat.S_IWRITE | stat.S_IWGRP)
  3228. os.remove(fact_def_file_path)
  3229. # recreate a new factory defaults file and save the factory defaults data into it
  3230. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  3231. json.dump(self.defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3232. f_f_def_s.close()
  3233. # and then make the factory_defaults.FlatConfig file read_only so it can't be modified after creation.
  3234. os.chmod(fact_def_file_path, S_IREAD | S_IRGRP | S_IROTH)
  3235. except Exception as e:
  3236. log.debug("App.load_defaults() -> deleting old factory defaults file -> %s" % str(e))
  3237. self.old_defaults_found = True
  3238. else:
  3239. self.defaults.update(defaults)
  3240. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3241. def on_import_preferences(self):
  3242. """
  3243. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  3244. ``self.defaults``.
  3245. :return: None
  3246. """
  3247. self.report_usage("on_import_preferences")
  3248. App.log.debug("on_import_preferences()")
  3249. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3250. try:
  3251. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3252. directory=self.data_path,
  3253. filter=filter_)
  3254. except TypeError:
  3255. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3256. filter=filter_)
  3257. filename = str(filename)
  3258. if filename == "":
  3259. self.inform.emit('[WARNING_NOTCL] %s' %
  3260. _("FlatCAM preferences import cancelled."))
  3261. else:
  3262. try:
  3263. f = open(filename)
  3264. options = f.read()
  3265. f.close()
  3266. except IOError:
  3267. self.log.error("Could not load defaults file.")
  3268. self.inform.emit('[ERROR_NOTCL] %s' %
  3269. _("Could not load defaults file."))
  3270. return
  3271. try:
  3272. defaults_from_file = json.loads(options)
  3273. except Exception:
  3274. e = sys.exc_info()[0]
  3275. App.log.error(str(e))
  3276. self.inform.emit('[ERROR_NOTCL] %s' %
  3277. _("Failed to parse defaults file."))
  3278. return
  3279. self.defaults.update(defaults_from_file)
  3280. self.on_preferences_edited()
  3281. self.inform.emit('[success] %s: %s' %
  3282. (_("Imported Defaults from"), filename))
  3283. def on_export_preferences(self):
  3284. """
  3285. Save the defaults dictionary to a file.
  3286. :return: None
  3287. """
  3288. self.report_usage("on_export_preferences")
  3289. App.log.debug("on_export_preferences()")
  3290. defaults_file_content = None
  3291. self.date = str(datetime.today()).rpartition('.')[0]
  3292. self.date = ''.join(c for c in self.date if c not in ':-')
  3293. self.date = self.date.replace(' ', '_')
  3294. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3295. try:
  3296. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3297. caption=_("Export FlatCAM Preferences"),
  3298. directory=self.data_path + '/preferences_' + self.date,
  3299. filter=filter__
  3300. )
  3301. except TypeError:
  3302. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3303. filter=filter__)
  3304. filename = str(filename)
  3305. defaults_from_file = {}
  3306. if filename == "":
  3307. self.inform.emit('[WARNING_NOTCL] %s' %
  3308. _("FlatCAM preferences export cancelled."))
  3309. return
  3310. else:
  3311. try:
  3312. f = open(filename, 'w')
  3313. defaults_file_content = f.read()
  3314. f.close()
  3315. except PermissionError:
  3316. self.inform.emit('[WARNING] %s' %
  3317. _("Permission denied, saving not possible.\n"
  3318. "Most likely another app is holding the file open and not accessible."))
  3319. return
  3320. except IOError:
  3321. App.log.debug('Creating a new preferences file ...')
  3322. f = open(filename, 'w')
  3323. json.dump({}, f)
  3324. f.close()
  3325. except Exception:
  3326. e = sys.exc_info()[0]
  3327. App.log.error("Could not load defaults file.")
  3328. App.log.error(str(e))
  3329. self.inform.emit('[ERROR_NOTCL] %s' %
  3330. _("Could not load preferences file."))
  3331. return
  3332. try:
  3333. defaults_from_file = json.loads(defaults_file_content)
  3334. except Exception:
  3335. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3336. # Update options
  3337. self.defaults_read_form()
  3338. defaults_from_file.update(self.defaults)
  3339. self.propagate_defaults(silent=True)
  3340. # Save update options
  3341. try:
  3342. f = open(filename, "w")
  3343. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3344. f.close()
  3345. except Exception:
  3346. self.inform.emit('[ERROR_NOTCL] %s' %
  3347. _("Failed to write defaults to file."))
  3348. return
  3349. if self.defaults["global_open_style"] is False:
  3350. self.file_opened.emit("preferences", filename)
  3351. self.file_saved.emit("preferences", filename)
  3352. self.inform.emit('[success] %s: %s' %
  3353. (_("Exported preferences to"), filename))
  3354. def on_preferences_open_folder(self):
  3355. """
  3356. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3357. :return: None
  3358. """
  3359. self.report_usage("on_preferences_open_folder()")
  3360. if sys.platform == 'win32':
  3361. subprocess.Popen('explorer %s' % self.data_path)
  3362. elif sys.platform == 'darwin':
  3363. os.system('open "%s"' % self.data_path)
  3364. else:
  3365. subprocess.Popen(['xdg-open', self.data_path])
  3366. self.inform.emit('[success] %s' %
  3367. _("FlatCAM Preferences Folder opened."))
  3368. def save_geometry(self, x, y, width, height, notebook_width):
  3369. """
  3370. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3371. launch of the application.
  3372. :param x: X position of the main window
  3373. :param y: Y position of the main window
  3374. :param width: width of the main window
  3375. :param height: height of the main window
  3376. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3377. :return: None
  3378. """
  3379. self.defaults["global_def_win_x"] = x
  3380. self.defaults["global_def_win_y"] = y
  3381. self.defaults["global_def_win_w"] = width
  3382. self.defaults["global_def_win_h"] = height
  3383. self.defaults["global_def_notebook_width"] = notebook_width
  3384. self.save_defaults()
  3385. def restore_main_win_geom(self):
  3386. try:
  3387. self.ui.setGeometry(self.defaults["global_def_win_x"],
  3388. self.defaults["global_def_win_y"],
  3389. self.defaults["global_def_win_w"],
  3390. self.defaults["global_def_win_h"])
  3391. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  3392. except KeyError as e:
  3393. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  3394. def message_dialog(self, title, message, kind="info"):
  3395. """
  3396. Builds and show a custom QMessageBox to be used in FlatCAM.
  3397. :param title: title of the QMessageBox
  3398. :param message: message to be displayed
  3399. :param kind: type of QMessageBox; will display a specific icon.
  3400. :return:
  3401. """
  3402. icon = {"info": QtWidgets.QMessageBox.Information,
  3403. "warning": QtWidgets.QMessageBox.Warning,
  3404. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3405. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3406. dlg.setText(message)
  3407. dlg.exec_()
  3408. def register_recent(self, kind, filename):
  3409. """
  3410. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3411. dictionary.
  3412. :param kind: type of file that was opened
  3413. :param filename: the path and file name for the file that was opened
  3414. :return:
  3415. """
  3416. self.log.debug("register_recent()")
  3417. self.log.debug(" %s" % kind)
  3418. self.log.debug(" %s" % filename)
  3419. record = {'kind': str(kind), 'filename': str(filename)}
  3420. if record in self.recent:
  3421. return
  3422. if record in self.recent_projects:
  3423. return
  3424. if record['kind'] == 'project':
  3425. self.recent_projects.insert(0, record)
  3426. else:
  3427. self.recent.insert(0, record)
  3428. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3429. self.recent.pop()
  3430. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3431. self.recent_projects.pop()
  3432. try:
  3433. f = open(self.data_path + '/recent.json', 'w')
  3434. except IOError:
  3435. App.log.error("Failed to open recent items file for writing.")
  3436. self.inform.emit('[ERROR_NOTCL] %s' %
  3437. _('Failed to open recent files file for writing.'))
  3438. return
  3439. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3440. f.close()
  3441. try:
  3442. fp = open(self.data_path + '/recent_projects.json', 'w')
  3443. except IOError:
  3444. App.log.error("Failed to open recent items file for writing.")
  3445. self.inform.emit('[ERROR_NOTCL] %s' %
  3446. _('Failed to open recent projects file for writing.'))
  3447. return
  3448. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3449. fp.close()
  3450. # Re-build the recent items menu
  3451. self.setup_recent_items()
  3452. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3453. """
  3454. Creates a new specialized FlatCAMObj and attaches it to the application,
  3455. this is, updates the GUI accordingly, any other records and plots it.
  3456. This method is thread-safe.
  3457. Notes:
  3458. * If the name is in use, the self.collection will modify it
  3459. when appending it to the collection. There is no need to handle
  3460. name conflicts here.
  3461. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3462. :type kind: str
  3463. :param name: Name for the object.
  3464. :type name: str
  3465. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3466. The function is called with 2 parameters: the new object and the App instance.
  3467. :type initialize: function
  3468. :param active:
  3469. :param fit:
  3470. :param plot: If to plot the resulting object
  3471. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3472. self.colleaction
  3473. :return: None
  3474. :rtype: None
  3475. """
  3476. App.log.debug("new_object()")
  3477. obj_plot = plot
  3478. obj_autoselected = autoselected
  3479. t0 = time.time() # Debug
  3480. # ## Create object
  3481. classdict = {
  3482. "gerber": FlatCAMGerber,
  3483. "excellon": FlatCAMExcellon,
  3484. "cncjob": FlatCAMCNCjob,
  3485. "geometry": FlatCAMGeometry,
  3486. "script": FlatCAMScript,
  3487. "document": FlatCAMDocument
  3488. }
  3489. App.log.debug("Calling object constructor...")
  3490. # Object creation/instantiation
  3491. obj = classdict[kind](name)
  3492. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3493. # IMPORTANT
  3494. # The key names in defaults and options dictionary's are not random:
  3495. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3496. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  3497. # copied to self.options. After that, below, depending on the type of
  3498. # object that is created, it will strip the name of the object and the underline (if the original key was
  3499. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3500. # "toolchange"
  3501. for option in self.options:
  3502. if option.find(kind + "_") == 0:
  3503. oname = option[len(kind) + 1:]
  3504. obj.options[oname] = self.options[option]
  3505. obj.isHovering = False
  3506. obj.notHovering = True
  3507. # Initialize as per user request
  3508. # User must take care to implement initialize
  3509. # in a thread-safe way as is is likely that we
  3510. # have been invoked in a separate thread.
  3511. t1 = time.time()
  3512. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3513. try:
  3514. return_value = initialize(obj, self)
  3515. except Exception as e:
  3516. msg = '[ERROR_NOTCL] %s' % \
  3517. _("An internal error has ocurred. See shell.\n")
  3518. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3519. msg += traceback.format_exc()
  3520. self.inform.emit(msg)
  3521. # if str(e) == "Empty Geometry":
  3522. # self.inform.emit("[ERROR_NOTCL] )
  3523. # else:
  3524. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3525. return "fail"
  3526. t2 = time.time()
  3527. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3528. if return_value == 'fail':
  3529. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3530. return "fail"
  3531. # Check units and convert if necessary
  3532. # This condition CAN be true because initialize() can change obj.units
  3533. if self.options["units"].upper() != obj.units.upper():
  3534. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  3535. obj.convert_units(self.options["units"])
  3536. t3 = time.time()
  3537. self.log.debug("%f seconds converting units." % (t3 - t2))
  3538. # Create the bounding box for the object and then add the results to the obj.options
  3539. # But not for Scripts or for Documents
  3540. if kind != 'document' and kind != 'script':
  3541. try:
  3542. xmin, ymin, xmax, ymax = obj.bounds()
  3543. obj.options['xmin'] = xmin
  3544. obj.options['ymin'] = ymin
  3545. obj.options['xmax'] = xmax
  3546. obj.options['ymax'] = ymax
  3547. except Exception as e:
  3548. log.warning("The object has no bounds properties. %s" % str(e))
  3549. return "fail"
  3550. # update the KeyWords list with the name of the file
  3551. self.myKeywords.append(obj.options['name'])
  3552. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3553. # Move the object to the main thread and let the app know that it is available.
  3554. obj.moveToThread(self.main_thread)
  3555. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3556. return obj
  3557. def new_excellon_object(self):
  3558. """
  3559. Creates a new, blank Excellon object.
  3560. :return: None
  3561. """
  3562. self.report_usage("new_excellon_object()")
  3563. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3564. def new_geometry_object(self):
  3565. """
  3566. Creates a new, blank and single-tool Geometry object.
  3567. :return: None
  3568. """
  3569. self.report_usage("new_geometry_object()")
  3570. def initialize(obj, app):
  3571. obj.multitool = False
  3572. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3573. def new_gerber_object(self):
  3574. """
  3575. Creates a new, blank Gerber object.
  3576. :return: None
  3577. """
  3578. self.report_usage("new_gerber_object()")
  3579. def initialize(grb_obj, app):
  3580. grb_obj.multitool = False
  3581. grb_obj.source_file = []
  3582. grb_obj.multigeo = False
  3583. grb_obj.follow = False
  3584. grb_obj.apertures = {}
  3585. grb_obj.solid_geometry = []
  3586. try:
  3587. grb_obj.options['xmin'] = 0
  3588. grb_obj.options['ymin'] = 0
  3589. grb_obj.options['xmax'] = 0
  3590. grb_obj.options['ymax'] = 0
  3591. except KeyError:
  3592. pass
  3593. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3594. def new_script_object(self, name=None, text=None):
  3595. """
  3596. Creates a new, blank TCL Script object.
  3597. :param name: a name for the new object
  3598. :param text: pass a source file to the newly created script to be loaded in it
  3599. :return: None
  3600. """
  3601. self.report_usage("new_script_object()")
  3602. if text is not None:
  3603. new_source_file = text
  3604. else:
  3605. commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  3606. "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n"\
  3607. "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  3608. "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n"\
  3609. "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  3610. "ListSys, MillDrills,\n"\
  3611. "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  3612. "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"\
  3613. "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  3614. "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  3615. "# SubtractRectangle, Version, WriteGCode\n"
  3616. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  3617. '# %s:\n' % _('TCL Tutorial is here') + \
  3618. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  3619. '# %s:\n' % _("FlatCAM commands list")
  3620. new_source_file += commands_list + '\n'
  3621. def initialize(obj, app):
  3622. obj.source_file = deepcopy(new_source_file)
  3623. if name is None:
  3624. outname = 'new_script'
  3625. else:
  3626. outname = name
  3627. self.new_object('script', outname, initialize, plot=False)
  3628. def new_document_object(self):
  3629. """
  3630. Creates a new, blank Document object.
  3631. :return: None
  3632. """
  3633. self.report_usage("new_document_object()")
  3634. def initialize(obj, app):
  3635. obj.source_file = ""
  3636. self.new_object('document', 'new_document', initialize, plot=False)
  3637. def on_object_created(self, obj, plot, auto_select):
  3638. """
  3639. Event callback for object creation.
  3640. It will add the new object to the collection. After that it will plot the object in a threaded way
  3641. :param obj: The newly created FlatCAM object.
  3642. :param plot: if the newly create object t obe plotted
  3643. :param auto_select: if the newly created object to be autoselected after creation
  3644. :return: None
  3645. """
  3646. t0 = time.time() # DEBUG
  3647. self.log.debug("on_object_created()")
  3648. # The Collection might change the name if there is a collision
  3649. self.collection.append(obj)
  3650. # after adding the object to the collection always update the list of objects that are in the collection
  3651. self.all_objects_list = self.collection.get_list()
  3652. # self.inform.emit('[selected] %s created & selected: %s' %
  3653. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3654. if obj.kind == 'gerber':
  3655. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3656. kind=obj.kind.capitalize(),
  3657. color='green',
  3658. name=str(obj.options['name']), tx=_("created/selected"))
  3659. )
  3660. elif obj.kind == 'excellon':
  3661. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3662. kind=obj.kind.capitalize(),
  3663. color='brown',
  3664. name=str(obj.options['name']), tx=_("created/selected"))
  3665. )
  3666. elif obj.kind == 'cncjob':
  3667. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3668. kind=obj.kind.capitalize(),
  3669. color='blue',
  3670. name=str(obj.options['name']), tx=_("created/selected"))
  3671. )
  3672. elif obj.kind == 'geometry':
  3673. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3674. kind=obj.kind.capitalize(),
  3675. color='red',
  3676. name=str(obj.options['name']), tx=_("created/selected"))
  3677. )
  3678. elif obj.kind == 'script':
  3679. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3680. kind=obj.kind.capitalize(),
  3681. color='orange',
  3682. name=str(obj.options['name']), tx=_("created/selected"))
  3683. )
  3684. elif obj.kind == 'document':
  3685. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3686. kind=obj.kind.capitalize(),
  3687. color='darkCyan',
  3688. name=str(obj.options['name']), tx=_("created/selected"))
  3689. )
  3690. # update the SHELL auto-completer model with the name of the new object
  3691. self.shell._edit.set_model_data(self.myKeywords)
  3692. if auto_select:
  3693. # select the just opened object but deselect the previous ones
  3694. self.collection.set_all_inactive()
  3695. self.collection.set_active(obj.options["name"])
  3696. else:
  3697. self.collection.set_all_inactive()
  3698. # here it is done the object plotting
  3699. def worker_task(t_obj):
  3700. with self.proc_container.new(_("Plotting")):
  3701. if isinstance(t_obj, FlatCAMCNCjob):
  3702. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3703. else:
  3704. t_obj.plot()
  3705. t1 = time.time() # DEBUG
  3706. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3707. self.object_plotted.emit(t_obj)
  3708. # Send to worker
  3709. # self.worker.add_task(worker_task, [self])
  3710. if plot is True:
  3711. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3712. def on_object_changed(self, obj):
  3713. """
  3714. Called whenever the geometry of the object was changed in some way.
  3715. This require the update of it's bounding values so it can be the selected on canvas.
  3716. Update the bounding box data from obj.options
  3717. :param obj: the object that was changed
  3718. :return: None
  3719. """
  3720. xmin, ymin, xmax, ymax = obj.bounds()
  3721. obj.options['xmin'] = xmin
  3722. obj.options['ymin'] = ymin
  3723. obj.options['xmax'] = xmax
  3724. obj.options['ymax'] = ymax
  3725. log.debug("Object changed, updating the bounding box data on self.options")
  3726. # delete the old selection shape
  3727. self.delete_selection_shape()
  3728. self.should_we_save = True
  3729. def on_object_plotted(self):
  3730. """
  3731. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3732. :return: None
  3733. """
  3734. self.on_zoom_fit(None)
  3735. def on_about(self):
  3736. """
  3737. Displays the "about" dialog found in the Menu --> Help.
  3738. :return: None
  3739. """
  3740. self.report_usage("on_about")
  3741. version = self.version
  3742. version_date = self.version_date
  3743. beta = self.beta
  3744. class AboutDialog(QtWidgets.QDialog):
  3745. def __init__(self, app, parent=None):
  3746. QtWidgets.QDialog.__init__(self, parent)
  3747. self.app = app
  3748. # Icon and title
  3749. self.setWindowIcon(parent.app_icon)
  3750. self.setWindowTitle(_("About FlatCAM"))
  3751. self.resize(600, 200)
  3752. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3753. # self.setStyleSheet(
  3754. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3755. # "background-attachment: fixed"
  3756. # )
  3757. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  3758. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3759. # palette = QtGui.QPalette()
  3760. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3761. # self.setPalette(palette)
  3762. logo = QtWidgets.QLabel()
  3763. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  3764. title = QtWidgets.QLabel(
  3765. "<font size=8><B>FlatCAM</B></font><BR>"
  3766. "{title}<BR>"
  3767. "<BR>"
  3768. "<BR>"
  3769. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3770. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3771. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3772. "<B>{issue}</B></a><BR>".format(
  3773. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3774. devel=_("Development"),
  3775. down=_("DOWNLOAD"),
  3776. issue=_("Issue tracker"))
  3777. )
  3778. title.setOpenExternalLinks(True)
  3779. closebtn = QtWidgets.QPushButton(_("Close"))
  3780. tab_widget = QtWidgets.QTabWidget()
  3781. description_label = QtWidgets.QLabel(
  3782. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3783. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3784. version=version,
  3785. beta=('BETA' if beta else ''),
  3786. date=version_date,
  3787. arch=platform.architecture()[0])
  3788. )
  3789. description_label.setOpenExternalLinks(True)
  3790. lic_lbl_header = QtWidgets.QLabel(
  3791. '%s:<br>%s<br>' % (
  3792. _('Licensed under the MIT license'),
  3793. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  3794. "http://www.opensource.org/licenses/mit-license.php</a>"
  3795. )
  3796. )
  3797. lic_lbl_header.setOpenExternalLinks(True)
  3798. lic_lbl_body = QtWidgets.QLabel(
  3799. _(
  3800. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3801. 'of this software and associated documentation files (the "Software"), to deal\n'
  3802. 'in the Software without restriction, including without limitation the rights\n'
  3803. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3804. 'copies of the Software, and to permit persons to whom the Software is\n'
  3805. 'furnished to do so, subject to the following conditions:\n\n'
  3806. 'The above copyright notice and this permission notice shall be included in\n'
  3807. 'all copies or substantial portions of the Software.\n\n'
  3808. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3809. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3810. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3811. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3812. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3813. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3814. 'THE SOFTWARE.'
  3815. )
  3816. )
  3817. attributions_label = QtWidgets.QLabel(
  3818. _(
  3819. 'Some of the icons used are from the following sources:<br>'
  3820. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  3821. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  3822. 'title="Flaticon">www.flaticon.com</a></div>'
  3823. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  3824. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  3825. )
  3826. )
  3827. # layouts
  3828. layout1 = QtWidgets.QVBoxLayout()
  3829. layout1_1 = QtWidgets.QHBoxLayout()
  3830. layout1_2 = QtWidgets.QHBoxLayout()
  3831. layout2 = QtWidgets.QHBoxLayout()
  3832. layout3 = QtWidgets.QHBoxLayout()
  3833. self.setLayout(layout1)
  3834. layout1.addLayout(layout1_1)
  3835. layout1.addLayout(layout1_2)
  3836. layout1.addLayout(layout2)
  3837. layout1.addLayout(layout3)
  3838. layout1_1.addStretch()
  3839. layout1_1.addWidget(description_label)
  3840. layout1_2.addWidget(tab_widget)
  3841. self.splash_tab = QtWidgets.QWidget()
  3842. self.splash_tab.setObjectName("splash_about")
  3843. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3844. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3845. tab_widget.addTab(self.splash_tab, _("Splash"))
  3846. self.programmmers_tab = QtWidgets.QWidget()
  3847. self.programmmers_tab.setObjectName("programmers_about")
  3848. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3849. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3850. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3851. self.translators_tab = QtWidgets.QWidget()
  3852. self.translators_tab.setObjectName("translators_about")
  3853. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3854. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3855. tab_widget.addTab(self.translators_tab, _("Translators"))
  3856. self.license_tab = QtWidgets.QWidget()
  3857. self.license_tab.setObjectName("license_about")
  3858. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3859. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3860. tab_widget.addTab(self.license_tab, _("License"))
  3861. self.attributions_tab = QtWidgets.QWidget()
  3862. self.attributions_tab.setObjectName("attributions_about")
  3863. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  3864. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  3865. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  3866. self.splash_tab_layout.addWidget(logo, stretch=0)
  3867. self.splash_tab_layout.addWidget(title, stretch=1)
  3868. pal = QtGui.QPalette()
  3869. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3870. self.prog_grid_lay = QtWidgets.QGridLayout()
  3871. self.prog_grid_lay.setHorizontalSpacing(20)
  3872. self.prog_grid_lay.setColumnStretch(0, 0)
  3873. self.prog_grid_lay.setColumnStretch(2, 1)
  3874. prog_widget = QtWidgets.QWidget()
  3875. prog_widget.setLayout(self.prog_grid_lay)
  3876. prog_scroll = QtWidgets.QScrollArea()
  3877. prog_scroll.setWidget(prog_widget)
  3878. prog_scroll.setWidgetResizable(True)
  3879. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3880. prog_scroll.setPalette(pal)
  3881. self.programmmers_tab_layout.addWidget(prog_scroll)
  3882. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  3883. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  3884. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3885. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  3886. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  3887. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  3888. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  3889. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  3890. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  3891. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  3892. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  3893. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  3894. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  3895. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  3896. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  3897. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  3898. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  3899. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 11, 0)
  3900. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  3901. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  3902. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 14, 0)
  3903. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 12, 0)
  3904. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 15, 0)
  3905. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 16, 0)
  3906. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 17, 0)
  3907. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 18, 0)
  3908. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 19, 0)
  3909. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 20, 0)
  3910. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 21, 0)
  3911. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 22, 0)
  3912. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 23, 0)
  3913. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 24, 0)
  3914. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 25, 0)
  3915. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 26, 0)
  3916. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 27, 0)
  3917. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 28, 0)
  3918. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 29, 0)
  3919. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 30, 0)
  3920. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 31, 0)
  3921. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 34, 0)
  3922. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  3923. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  3924. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  3925. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  3926. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  3927. self.translator_grid_lay = QtWidgets.QGridLayout()
  3928. self.translator_grid_lay.setColumnStretch(0, 0)
  3929. self.translator_grid_lay.setColumnStretch(1, 0)
  3930. self.translator_grid_lay.setColumnStretch(2, 1)
  3931. self.translator_grid_lay.setColumnStretch(3, 0)
  3932. # trans_widget = QtWidgets.QWidget()
  3933. # trans_widget.setLayout(self.translator_grid_lay)
  3934. # self.translators_tab_layout.addWidget(trans_widget)
  3935. # self.translators_tab_layout.addStretch()
  3936. trans_widget = QtWidgets.QWidget()
  3937. trans_widget.setLayout(self.translator_grid_lay)
  3938. trans_scroll = QtWidgets.QScrollArea()
  3939. trans_scroll.setWidget(trans_widget)
  3940. trans_scroll.setWidgetResizable(True)
  3941. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3942. trans_scroll.setPalette(pal)
  3943. self.translators_tab_layout.addWidget(trans_scroll)
  3944. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3945. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3946. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  3947. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  3948. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  3949. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3950. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  3951. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  3952. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  3953. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  3954. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  3955. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  3956. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 3, 1)
  3957. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, @detlefeckardt"), 3, 2)
  3958. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  3959. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  3960. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  3961. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  3962. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  3963. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  3964. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  3965. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  3966. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 6, 1)
  3967. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 6, 2)
  3968. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  3969. self.translator_grid_lay.setColumnStretch(0, 0)
  3970. self.translators_tab_layout.addStretch()
  3971. self.license_tab_layout.addWidget(lic_lbl_header)
  3972. self.license_tab_layout.addWidget(lic_lbl_body)
  3973. self.license_tab_layout.addStretch()
  3974. self.attributions_tab_layout.addWidget(attributions_label)
  3975. self.attributions_tab_layout.addStretch()
  3976. layout3.addStretch()
  3977. layout3.addWidget(closebtn)
  3978. closebtn.clicked.connect(self.accept)
  3979. AboutDialog(app=self, parent=self.ui).exec_()
  3980. def install_bookmarks(self, book_dict=None):
  3981. """
  3982. Install the bookmarks actions in the Help menu -> Bookmarks
  3983. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  3984. :return: None
  3985. """
  3986. if book_dict is None:
  3987. self.defaults["global_bookmarks"].update(
  3988. {
  3989. '1': ['FlatCAM', "http://flatcam.org"],
  3990. '2': ['Backup Site', ""]
  3991. }
  3992. )
  3993. else:
  3994. self.defaults["global_bookmarks"].clear()
  3995. self.defaults["global_bookmarks"].update(book_dict)
  3996. # first try to disconnect if somehow they get connected from elsewhere
  3997. for act in self.ui.menuhelp_bookmarks.actions():
  3998. try:
  3999. act.triggered.disconnect()
  4000. except TypeError:
  4001. pass
  4002. # clear all actions except the last one who is the Bookmark manager
  4003. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  4004. pass
  4005. else:
  4006. self.ui.menuhelp_bookmarks.removeAction(act)
  4007. bm_limit = int(self.defaults["global_bookmarks_limit"])
  4008. if self.defaults["global_bookmarks"]:
  4009. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  4010. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  4011. # the JSON is first making the keys as strings (therefore I have to use strings too
  4012. # or do the conversion :(
  4013. # )
  4014. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  4015. # the '10' entry jsut after '1' therefore ordering as strings
  4016. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  4017. key=lambda x: int(x[0]))
  4018. for entry, bookmark in sorted_bookmarks:
  4019. title = bookmark[0]
  4020. weblink = bookmark[1]
  4021. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  4022. act.setText(title)
  4023. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  4024. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  4025. if title == 'Backup Site' and weblink == "":
  4026. act.triggered.connect(self.on_backup_site)
  4027. else:
  4028. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  4029. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  4030. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  4031. def on_bookmarks_manager(self):
  4032. """
  4033. Adds the bookmark manager in a Tab in Plot Area
  4034. :return:
  4035. """
  4036. for idx in range(self.ui.plot_tab_area.count()):
  4037. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  4038. # there can be only one instance of Bookmark Manager at one time
  4039. return
  4040. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  4041. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  4042. # add the tab if it was closed
  4043. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  4044. # delete the absolute and relative position and messages in the infobar
  4045. self.ui.position_label.setText("")
  4046. self.ui.rel_position_label.setText("")
  4047. # Switch plot_area to preferences page
  4048. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  4049. def on_backup_site(self):
  4050. msgbox = QtWidgets.QMessageBox()
  4051. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  4052. "1. FlatCAM.org website is down\n"
  4053. "2. Someone forked FlatCAM project and wants to point\n"
  4054. "to his own website\n\n"
  4055. "If you can't get any informations about FlatCAM beta\n"
  4056. "use the YouTube channel link from the Help menu."))
  4057. msgbox.setWindowTitle(_("Alternative website"))
  4058. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  4059. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  4060. msgbox.setDefaultButton(bt_yes)
  4061. msgbox.exec_()
  4062. # response = msgbox.clickedButton()
  4063. def on_file_savedefaults(self):
  4064. """
  4065. Callback for menu item File->Save Defaults. Saves application default options
  4066. ``self.defaults`` to current_defaults.FlatConfig.
  4067. :return: None
  4068. """
  4069. self.save_defaults()
  4070. # def on_app_exit(self):
  4071. # self.report_usage("on_app_exit()")
  4072. #
  4073. # if self.collection.get_list():
  4074. # msgbox = QtWidgets.QMessageBox()
  4075. # # msgbox.setText("<B>Save changes ...</B>")
  4076. # msgbox.setText("There are files/objects opened in FlatCAM. "
  4077. # "\n"
  4078. # "Do you want to Save the project?")
  4079. # msgbox.setWindowTitle("Save changes")
  4080. # msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4081. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  4082. # QtWidgets.QMessageBox.Cancel)
  4083. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  4084. #
  4085. # response = msgbox.exec_()
  4086. #
  4087. # if response == QtWidgets.QMessageBox.Yes:
  4088. # self.on_file_saveprojectas(thread=False)
  4089. # elif response == QtWidgets.QMessageBox.Cancel:
  4090. # return
  4091. # self.save_defaults()
  4092. # else:
  4093. # self.save_defaults()
  4094. # log.debug("Application defaults saved ... Exit event.")
  4095. # QtWidgets.qApp.quit()
  4096. def save_defaults(self, silent=False, data_path=None, first_time=False):
  4097. """
  4098. Saves application default options
  4099. ``self.defaults`` to current_defaults.FlatConfig file.
  4100. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  4101. used at the next launch of the application.
  4102. :param silent: whether to display a message in status bar or not; boolean
  4103. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  4104. When the application is portable it should be a mobile location.
  4105. :return: None
  4106. """
  4107. self.report_usage("save_defaults")
  4108. if data_path is None:
  4109. data_path = self.data_path
  4110. # Read options from file
  4111. try:
  4112. f = open(data_path + "/current_defaults.FlatConfig")
  4113. defaults_file_content = f.read()
  4114. f.close()
  4115. except Exception:
  4116. e = sys.exc_info()[0]
  4117. App.log.error("Could not load defaults file.")
  4118. App.log.error(str(e))
  4119. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load defaults file."))
  4120. return
  4121. try:
  4122. defaults = json.loads(defaults_file_content)
  4123. except Exception:
  4124. e = sys.exc_info()[0]
  4125. App.log.error("Failed to parse defaults file.")
  4126. App.log.error(str(e))
  4127. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse defaults file."))
  4128. return
  4129. # Update options
  4130. self.defaults_read_form()
  4131. defaults.update(self.defaults)
  4132. self.propagate_defaults(silent=True)
  4133. # Save the toolbar view
  4134. tb_status = 0
  4135. if self.ui.toolbarfile.isVisible():
  4136. tb_status += 1
  4137. if self.ui.toolbargeo.isVisible():
  4138. tb_status += 2
  4139. if self.ui.toolbarview.isVisible():
  4140. tb_status += 4
  4141. if self.ui.toolbartools.isVisible():
  4142. tb_status += 8
  4143. if self.ui.exc_edit_toolbar.isVisible():
  4144. tb_status += 16
  4145. if self.ui.geo_edit_toolbar.isVisible():
  4146. tb_status += 32
  4147. if self.ui.grb_edit_toolbar.isVisible():
  4148. tb_status += 64
  4149. if self.ui.snap_toolbar.isVisible():
  4150. tb_status += 128
  4151. if self.ui.toolbarshell.isVisible():
  4152. tb_status += 256
  4153. if first_time is False:
  4154. self.defaults["global_toolbar_view"] = tb_status
  4155. # Save update options
  4156. try:
  4157. f = open(data_path + "/current_defaults.FlatConfig", "w")
  4158. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  4159. f.close()
  4160. except Exception as e:
  4161. log.debug("App.save_defaults() --> %s" % str(e))
  4162. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write defaults to file."))
  4163. return
  4164. if not silent:
  4165. self.inform.emit('[success] %s' % _("Preferences saved."))
  4166. def save_factory_defaults(self, silent_message=False, data_path=None):
  4167. """
  4168. Saves application factory default options
  4169. ``self.defaults`` to factory_defaults.FlatConfig.
  4170. It's a one time job done just after the first install.
  4171. :param silent_message: whether to display a message in status bar or not; boolean
  4172. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  4173. When the application is portable it should be a mobile location.
  4174. :return: None
  4175. """
  4176. self.report_usage("save_factory_defaults")
  4177. if data_path is None:
  4178. data_path = self.data_path
  4179. # Read options from file
  4180. try:
  4181. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  4182. factory_defaults_file_content = f_f_def.read()
  4183. f_f_def.close()
  4184. except Exception:
  4185. e = sys.exc_info()[0]
  4186. App.log.error("Could not load factory defaults file.")
  4187. App.log.error(str(e))
  4188. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load factory defaults file."))
  4189. return
  4190. try:
  4191. factory_defaults = json.loads(factory_defaults_file_content)
  4192. except Exception:
  4193. e = sys.exc_info()[0]
  4194. App.log.error("Failed to parse factory defaults file.")
  4195. App.log.error(str(e))
  4196. if silent_message is False:
  4197. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse factory defaults file."))
  4198. return
  4199. # Update options
  4200. self.defaults_read_form()
  4201. factory_defaults.update(self.defaults)
  4202. self.propagate_defaults(silent=True)
  4203. # Save update options
  4204. try:
  4205. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  4206. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  4207. f_f_def_s.close()
  4208. except Exception as e:
  4209. log.debug("App.save_factory_default() save update --> %s" % str(e))
  4210. if silent_message is False:
  4211. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write factory defaults to file."))
  4212. return
  4213. if silent_message is False:
  4214. self.inform.emit(_("Factory defaults saved."))
  4215. def final_save(self):
  4216. """
  4217. Callback for doing a preferences save to file whenever the application is about to quit.
  4218. If the project has changes, it will ask the user to save the project.
  4219. :return: None
  4220. """
  4221. if self.save_in_progress:
  4222. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  4223. return
  4224. if self.should_we_save and self.collection.get_list():
  4225. msgbox = QtWidgets.QMessageBox()
  4226. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  4227. "\n"
  4228. "Do you want to Save the project?"))
  4229. msgbox.setWindowTitle(_("Save changes"))
  4230. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4231. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4232. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4233. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4234. msgbox.setDefaultButton(bt_yes)
  4235. msgbox.exec_()
  4236. response = msgbox.clickedButton()
  4237. if response == bt_yes:
  4238. try:
  4239. self.trayIcon.hide()
  4240. except Exception:
  4241. pass
  4242. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  4243. elif response == bt_no:
  4244. try:
  4245. self.trayIcon.hide()
  4246. except Exception:
  4247. pass
  4248. self.quit_application()
  4249. elif response == bt_cancel:
  4250. return
  4251. else:
  4252. try:
  4253. self.trayIcon.hide()
  4254. except Exception:
  4255. pass
  4256. self.quit_application()
  4257. def quit_application(self):
  4258. """
  4259. Called (as a pyslot or not) when the application is quit.
  4260. :return: None
  4261. """
  4262. self.save_defaults()
  4263. log.debug("App.final_save() --> App Defaults saved.")
  4264. if self.cmd_line_headless != 1:
  4265. # save app state to file
  4266. stgs = QSettings("Open Source", "FlatCAM")
  4267. stgs.setValue('saved_gui_state', self.ui.saveState())
  4268. stgs.setValue('maximized_gui', self.ui.isMaximized())
  4269. stgs.setValue(
  4270. 'language',
  4271. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  4272. )
  4273. stgs.setValue(
  4274. 'notebook_font_size',
  4275. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4276. )
  4277. stgs.setValue(
  4278. 'axis_font_size',
  4279. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  4280. )
  4281. stgs.setValue(
  4282. 'textbox_font_size',
  4283. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  4284. )
  4285. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  4286. stgs.setValue(
  4287. 'machinist',
  4288. 1 if self.ui.general_defaults_form.general_app_group.machinist_cb.get_value() else 0
  4289. )
  4290. # This will write the setting to the platform specific storage.
  4291. del stgs
  4292. log.debug("App.final_save() --> App UI state saved.")
  4293. QtWidgets.qApp.quit()
  4294. def on_portable_checked(self, state):
  4295. """
  4296. Callback called when the checkbox in Preferences GUI is checked.
  4297. It will set the application as portable by creating the preferences and recent files in the
  4298. 'config' folder found in the FlatCAM installation folder.
  4299. :param state: boolean, the state of the checkbox when clicked/checked
  4300. :return:
  4301. """
  4302. line_no = 0
  4303. data = None
  4304. if sys.platform != 'win32':
  4305. # this won't work in Linux or MacOS
  4306. return
  4307. # test if the app was frozen and choose the path for the configuration file
  4308. if getattr(sys, "frozen", False) is True:
  4309. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  4310. else:
  4311. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  4312. config_file = current_data_path + '\\configuration.txt'
  4313. try:
  4314. with open(config_file, 'r') as f:
  4315. try:
  4316. data = f.readlines()
  4317. except Exception as e:
  4318. log.debug('App.__init__() -->%s' % str(e))
  4319. return
  4320. except FileNotFoundError:
  4321. pass
  4322. for line in data:
  4323. line = line.strip('\n')
  4324. param = str(line).rpartition('=')
  4325. if param[0] == 'portable':
  4326. break
  4327. line_no += 1
  4328. if state:
  4329. data[line_no] = 'portable=True\n'
  4330. # create the new defauults files
  4331. # create current_defaults.FlatConfig file if there is none
  4332. try:
  4333. f = open(current_data_path + '/current_defaults.FlatConfig')
  4334. f.close()
  4335. except IOError:
  4336. App.log.debug('Creating empty current_defaults.FlatConfig')
  4337. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  4338. json.dump({}, f)
  4339. f.close()
  4340. # create factory_defaults.FlatConfig file if there is none
  4341. try:
  4342. f = open(current_data_path + '/factory_defaults.FlatConfig')
  4343. f.close()
  4344. except IOError:
  4345. App.log.debug('Creating empty factory_defaults.FlatConfig')
  4346. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  4347. json.dump({}, f)
  4348. f.close()
  4349. try:
  4350. f = open(current_data_path + '/recent.json')
  4351. f.close()
  4352. except IOError:
  4353. App.log.debug('Creating empty recent.json')
  4354. f = open(current_data_path + '/recent.json', 'w')
  4355. json.dump([], f)
  4356. f.close()
  4357. try:
  4358. fp = open(current_data_path + '/recent_projects.json')
  4359. fp.close()
  4360. except IOError:
  4361. App.log.debug('Creating empty recent_projects.json')
  4362. fp = open(current_data_path + '/recent_projects.json', 'w')
  4363. json.dump([], fp)
  4364. fp.close()
  4365. # save the current defaults to the new defaults file
  4366. self.save_defaults(silent=True, data_path=current_data_path)
  4367. self.save_factory_defaults(silent_message=True, data_path=current_data_path)
  4368. else:
  4369. data[line_no] = 'portable=False\n'
  4370. with open(config_file, 'w') as f:
  4371. f.writelines(data)
  4372. def on_toggle_shell(self):
  4373. """
  4374. Toggle shell: if is visible close it, if it is closed then open it
  4375. :return: None
  4376. """
  4377. self.report_usage("on_toggle_shell()")
  4378. if self.ui.shell_dock.isVisible():
  4379. self.ui.shell_dock.hide()
  4380. else:
  4381. self.ui.shell_dock.show()
  4382. def on_register_files(self, obj_type=None):
  4383. """
  4384. Called whenever there is a need to register file extensions with FlatCAM.
  4385. Works only in Windows and should be called only when FlatCAM is run in Windows.
  4386. :param obj_type: the type of object to be register for.
  4387. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  4388. :return: None
  4389. """
  4390. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  4391. new_reg_path = 'Software\\Classes\\'
  4392. # find if the current user is admin
  4393. try:
  4394. is_admin = os.getuid() == 0
  4395. except AttributeError:
  4396. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  4397. if is_admin is True:
  4398. root_path = winreg.HKEY_LOCAL_MACHINE
  4399. else:
  4400. root_path = winreg.HKEY_CURRENT_USER
  4401. # create the keys
  4402. def set_reg(name, root_path, new_reg_path, value):
  4403. try:
  4404. winreg.CreateKey(root_path, new_reg_path)
  4405. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4406. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4407. return True
  4408. except WindowsError:
  4409. return False
  4410. # delete key in registry
  4411. def delete_reg(root_path, reg_path, key_to_del):
  4412. key_to_del_path = reg_path + key_to_del
  4413. try:
  4414. winreg.DeleteKey(root_path, key_to_del_path)
  4415. return True
  4416. except WindowsError:
  4417. return False
  4418. if obj_type is None or obj_type == 'excellon':
  4419. exc_list = \
  4420. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4421. exc_list = [x for x in exc_list if x != '']
  4422. # register all keys in the Preferences window
  4423. for ext in exc_list:
  4424. new_k = new_reg_path + '.%s' % ext
  4425. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4426. # and unregister those that are no longer in the Preferences windows but are in the file
  4427. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4428. if ext not in exc_list:
  4429. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4430. # now write the updated extensions to the self.defaults
  4431. # new_ext = ''
  4432. # for ext in exc_list:
  4433. # new_ext = new_ext + ext + ', '
  4434. # self.defaults["fa_excellon"] = new_ext
  4435. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4436. if obj_type is None or obj_type == 'gcode':
  4437. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4438. gco_list = [x for x in gco_list if x != '']
  4439. # register all keys in the Preferences window
  4440. for ext in gco_list:
  4441. new_k = new_reg_path + '.%s' % ext
  4442. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4443. # and unregister those that are no longer in the Preferences windows but are in the file
  4444. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4445. if ext not in gco_list:
  4446. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4447. # now write the updated extensions to the self.defaults
  4448. # new_ext = ''
  4449. # for ext in gco_list:
  4450. # new_ext = new_ext + ext + ', '
  4451. # self.defaults["fa_gcode"] = new_ext
  4452. self.inform.emit('[success] %s' %
  4453. _("Selected GCode file extensions registered with FlatCAM."))
  4454. if obj_type is None or obj_type == 'gerber':
  4455. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4456. grb_list = [x for x in grb_list if x != '']
  4457. # register all keys in the Preferences window
  4458. for ext in grb_list:
  4459. new_k = new_reg_path + '.%s' % ext
  4460. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4461. # and unregister those that are no longer in the Preferences windows but are in the file
  4462. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4463. if ext not in grb_list:
  4464. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4465. # now write the updated extensions to the self.defaults
  4466. # new_ext = ''
  4467. # for ext in grb_list:
  4468. # new_ext = new_ext + ext + ', '
  4469. # self.defaults["fa_gerber"] = new_ext
  4470. self.inform.emit('[success] %s' %
  4471. _("Selected Gerber file extensions registered with FlatCAM."))
  4472. def add_extension(self, ext_type):
  4473. """
  4474. Add a file extension to the list for a specific object
  4475. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4476. :return:
  4477. """
  4478. if ext_type == 'excellon':
  4479. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4480. if new_ext == '':
  4481. return
  4482. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4483. if new_ext in old_val:
  4484. return
  4485. old_val.append(new_ext)
  4486. old_val.sort()
  4487. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4488. if ext_type == 'gcode':
  4489. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4490. if new_ext == '':
  4491. return
  4492. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4493. if new_ext in old_val:
  4494. return
  4495. old_val.append(new_ext)
  4496. old_val.sort()
  4497. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4498. if ext_type == 'gerber':
  4499. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4500. if new_ext == '':
  4501. return
  4502. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4503. if new_ext in old_val:
  4504. return
  4505. old_val.append(new_ext)
  4506. old_val.sort()
  4507. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4508. if ext_type == 'keyword':
  4509. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4510. if new_kw == '':
  4511. return
  4512. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4513. if new_kw in old_val:
  4514. return
  4515. old_val.append(new_kw)
  4516. old_val.sort()
  4517. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4518. # update the self.myKeywords so the model is updated
  4519. self.autocomplete_kw_list = \
  4520. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4521. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4522. self.shell._edit.set_model_data(self.myKeywords)
  4523. def del_extension(self, ext_type):
  4524. """
  4525. Remove a file extension from the list for a specific object
  4526. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4527. :return:
  4528. """
  4529. if ext_type == 'excellon':
  4530. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4531. if new_ext == '':
  4532. return
  4533. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4534. if new_ext not in old_val:
  4535. return
  4536. old_val.remove(new_ext)
  4537. old_val.sort()
  4538. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4539. if ext_type == 'gcode':
  4540. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4541. if new_ext == '':
  4542. return
  4543. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4544. if new_ext not in old_val:
  4545. return
  4546. old_val.remove(new_ext)
  4547. old_val.sort()
  4548. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4549. if ext_type == 'gerber':
  4550. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4551. if new_ext == '':
  4552. return
  4553. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4554. if new_ext not in old_val:
  4555. return
  4556. old_val.remove(new_ext)
  4557. old_val.sort()
  4558. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4559. if ext_type == 'keyword':
  4560. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4561. if new_kw == '':
  4562. return
  4563. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4564. if new_kw not in old_val:
  4565. return
  4566. old_val.remove(new_kw)
  4567. old_val.sort()
  4568. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4569. # update the self.myKeywords so the model is updated
  4570. self.autocomplete_kw_list = \
  4571. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4572. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4573. self.shell._edit.set_model_data(self.myKeywords)
  4574. def restore_extensions(self, ext_type):
  4575. """
  4576. Restore all file extensions associations with FlatCAM, for a specific object
  4577. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4578. :return:
  4579. """
  4580. if ext_type == 'excellon':
  4581. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4582. # for the ability to open Excellon files with .txt extension
  4583. new_exc_list = deepcopy(self.exc_list)
  4584. try:
  4585. new_exc_list.remove('txt')
  4586. except ValueError:
  4587. pass
  4588. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4589. if ext_type == 'gcode':
  4590. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4591. if ext_type == 'gerber':
  4592. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4593. if ext_type == 'keyword':
  4594. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4595. # update the self.myKeywords so the model is updated
  4596. self.autocomplete_kw_list = self.default_keywords
  4597. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4598. self.shell._edit.set_model_data(self.myKeywords)
  4599. def delete_all_extensions(self, ext_type):
  4600. """
  4601. Delete all file extensions associations with FlatCAM, for a specific object
  4602. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4603. :return:
  4604. """
  4605. if ext_type == 'excellon':
  4606. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4607. if ext_type == 'gcode':
  4608. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4609. if ext_type == 'gerber':
  4610. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4611. if ext_type == 'keyword':
  4612. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4613. # update the self.myKeywords so the model is updated
  4614. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4615. self.shell._edit.set_model_data(self.myKeywords)
  4616. def on_edit_join(self, name=None):
  4617. """
  4618. Callback for Edit->Join. Joins the selected geometry objects into
  4619. a new one.
  4620. :return: None
  4621. """
  4622. self.report_usage("on_edit_join()")
  4623. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4624. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4625. geo_type_set = set()
  4626. objs = self.collection.get_selected()
  4627. if len(objs) < 2:
  4628. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4629. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4630. return 'fail'
  4631. for obj in objs:
  4632. geo_type_set.add(obj.multigeo)
  4633. # if len(geo_type_list) == 1 means that all list elements are the same
  4634. if len(geo_type_set) != 1:
  4635. self.inform.emit('[ERROR] %s' %
  4636. _("Failed join. The Geometry objects are of different types.\n"
  4637. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4638. "convert from one to another and retry joining \n"
  4639. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4640. "the result may not be what was expected. \n"
  4641. "Check the generated GCODE."))
  4642. return
  4643. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4644. if True in geo_type_set:
  4645. def initialize(geo_obj, app):
  4646. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=True)
  4647. app.inform.emit('[success] %s.' % _("Multigeo. Geometry merging finished"))
  4648. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4649. for v in obj.tools.values():
  4650. v['data']['name'] = obj_name_multi
  4651. self.new_object("geometry", obj_name_multi, initialize)
  4652. else:
  4653. def initialize(geo_obj, app):
  4654. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=False)
  4655. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  4656. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4657. for v in obj.tools.values():
  4658. v['data']['name'] = obj_name_single
  4659. self.new_object("geometry", obj_name_single, initialize)
  4660. self.should_we_save = True
  4661. def on_edit_join_exc(self):
  4662. """
  4663. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4664. a new Excellon.
  4665. :return: None
  4666. """
  4667. self.report_usage("on_edit_join_exc()")
  4668. objs = self.collection.get_selected()
  4669. for obj in objs:
  4670. if not isinstance(obj, FlatCAMExcellon):
  4671. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  4672. return
  4673. if len(objs) < 2:
  4674. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4675. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4676. return 'fail'
  4677. def initialize(exc_obj, app):
  4678. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=exc_obj)
  4679. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  4680. self.new_object("excellon", 'Combo_Excellon', initialize)
  4681. self.should_we_save = True
  4682. def on_edit_join_grb(self):
  4683. """
  4684. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4685. a new Gerber object.
  4686. :return: None
  4687. """
  4688. self.report_usage("on_edit_join_grb()")
  4689. objs = self.collection.get_selected()
  4690. for obj in objs:
  4691. if not isinstance(obj, FlatCAMGerber):
  4692. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  4693. return
  4694. if len(objs) < 2:
  4695. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4696. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4697. return 'fail'
  4698. def initialize(grb_obj, app):
  4699. FlatCAMGerber.merge(self, grb_list=objs, grb_final=grb_obj)
  4700. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  4701. self.new_object("gerber", 'Combo_Gerber', initialize)
  4702. self.should_we_save = True
  4703. def on_convert_singlegeo_to_multigeo(self):
  4704. """
  4705. Called for converting a Geometry object from single-geo to multi-geo.
  4706. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4707. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4708. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4709. the solid-geometry of that tool.
  4710. :return: None
  4711. """
  4712. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4713. obj = self.collection.get_active()
  4714. if obj is None:
  4715. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  4716. return
  4717. if not isinstance(obj, FlatCAMGeometry):
  4718. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4719. return
  4720. obj.multigeo = True
  4721. for tooluid, dict_value in obj.tools.items():
  4722. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4723. if not isinstance(obj.solid_geometry, list):
  4724. obj.solid_geometry = [obj.solid_geometry]
  4725. obj.solid_geometry[:] = []
  4726. obj.plot()
  4727. self.should_we_save = True
  4728. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  4729. def on_convert_multigeo_to_singlegeo(self):
  4730. """
  4731. Called for converting a Geometry object from multi-geo to single-geo.
  4732. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4733. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4734. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4735. the solid-geometry of that tool.
  4736. :return: None
  4737. """
  4738. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4739. obj = self.collection.get_active()
  4740. if obj is None:
  4741. self.inform.emit('[ERROR_NOTCL] %s' %
  4742. _("Failed. Select a Geometry Object and try again."))
  4743. return
  4744. if not isinstance(obj, FlatCAMGeometry):
  4745. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4746. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4747. return
  4748. obj.multigeo = False
  4749. total_solid_geometry = []
  4750. for tooluid, dict_value in obj.tools.items():
  4751. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4752. # clear the original geometry
  4753. dict_value['solid_geometry'][:] = []
  4754. obj.solid_geometry = deepcopy(total_solid_geometry)
  4755. obj.plot()
  4756. self.should_we_save = True
  4757. self.inform.emit('[success] %s' %
  4758. _("A Geometry object was converted to SingleGeo type."))
  4759. def on_defaults_dict_change(self, field):
  4760. """
  4761. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4762. Edit -> Preferences tab window.
  4763. :param field: the key of the self.defaults dictionary that was changed.
  4764. :return: None
  4765. """
  4766. self.defaults_write_form_field(field)
  4767. if field == "units":
  4768. self.set_screen_units(self.defaults['units'])
  4769. def set_screen_units(self, units):
  4770. """
  4771. Set the FlatCAM units on the status bar.
  4772. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4773. :return: None
  4774. """
  4775. self.ui.units_label.setText("[" + units.lower() + "]")
  4776. def on_toggle_units_click(self):
  4777. try:
  4778. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4779. except (TypeError, AttributeError):
  4780. pass
  4781. if self.defaults["units"] == 'MM':
  4782. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4783. else:
  4784. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4785. self.on_toggle_units(no_pref=True)
  4786. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4787. lambda: self.on_toggle_units(no_pref=False))
  4788. def on_toggle_units(self, no_pref=False):
  4789. """
  4790. Callback for the Units radio-button change in the Preferences tab.
  4791. Changes the application's default units adn for the project too.
  4792. If changing the project's units, the change propagates to all of
  4793. the objects in the project.
  4794. :return: None
  4795. """
  4796. self.report_usage("on_toggle_units")
  4797. if self.toggle_units_ignore:
  4798. return
  4799. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4800. # If option is the same, then ignore
  4801. if new_units == self.defaults["units"].upper():
  4802. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4803. return
  4804. # Options to scale
  4805. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  4806. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  4807. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4808. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4809. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4810. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  4811. "excellon_editor_slot_lin_pitch",
  4812. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4813. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4814. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4815. "geometry_feedrate_probe", "geometry_startz",
  4816. 'cncjob_tooldia',
  4817. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4818. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  4819. "tools_nccnewdia",
  4820. "tools_2sided_drilldia", "tools_film_boundary",
  4821. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4822. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4823. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4824. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4825. "tools_transform_offset_y",
  4826. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4827. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4828. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4829. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4830. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  4831. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  4832. "tools_cr_h2h_val", "tools_cr_dh_val", "tools_fiducials_dia", "tools_fiducials_margin",
  4833. "tools_fiducials_mode", "tools_fiducials_second_pos", "tools_fiducials_type",
  4834. "tools_fiducials_line_thickness",
  4835. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  4836. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  4837. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  4838. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  4839. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  4840. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance"]
  4841. def scale_defaults(sfactor):
  4842. for dim in dimensions:
  4843. if dim == 'excellon_toolchangexy':
  4844. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4845. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4846. coords_xy[0] *= sfactor
  4847. coords_xy[1] *= sfactor
  4848. self.defaults['excellon_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  4849. self.decimals, coords_xy[1])
  4850. elif dim == 'geometry_toolchangexy':
  4851. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4852. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4853. coords_xy[0] *= sfactor
  4854. coords_xy[1] *= sfactor
  4855. self.defaults['geometry_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  4856. self.decimals, coords_xy[1])
  4857. elif dim == 'geometry_cnctooldia':
  4858. tools_diameters = []
  4859. try:
  4860. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4861. tools_diameters = [eval(a) for a in tools_string if a != '']
  4862. except Exception as e:
  4863. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4864. self.defaults['geometry_cnctooldia'] = ''
  4865. for t in range(len(tools_diameters)):
  4866. tools_diameters[t] *= sfactor
  4867. self.defaults['geometry_cnctooldia'] += "%.*f," % (self.decimals, tools_diameters[t])
  4868. elif dim == 'tools_ncctools':
  4869. ncctools = []
  4870. try:
  4871. tools_string = self.defaults["tools_ncctools"].split(",")
  4872. ncctools = [eval(a) for a in tools_string if a != '']
  4873. except Exception as e:
  4874. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4875. self.defaults['tools_ncctools'] = ''
  4876. for t in range(len(ncctools)):
  4877. ncctools[t] *= sfactor
  4878. self.defaults['tools_ncctools'] += "%.*f," % (self.decimals, ncctools[t])
  4879. elif dim == 'tools_solderpaste_tools':
  4880. sptools = []
  4881. try:
  4882. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4883. sptools = [eval(a) for a in tools_string if a != '']
  4884. except Exception as e:
  4885. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4886. self.defaults['tools_solderpaste_tools'] = ""
  4887. for t in range(len(sptools)):
  4888. sptools[t] *= sfactor
  4889. self.defaults['tools_solderpaste_tools'] += "%.*f," % (self.decimals, sptools[t])
  4890. elif dim == 'tools_solderpaste_xy_toolchange':
  4891. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4892. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4893. sp_coords[0] *= sfactor
  4894. sp_coords[1] *= sfactor
  4895. self.defaults['tools_solderpaste_xy_toolchange'] = "%.*f, %.*f" % (self.decimals, sp_coords[0],
  4896. self.decimals, sp_coords[1])
  4897. elif dim == 'global_gridx' or dim == 'global_gridy':
  4898. if new_units == 'IN':
  4899. val = 0.1
  4900. try:
  4901. val = float(self.defaults[dim]) * sfactor
  4902. except Exception as e:
  4903. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4904. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  4905. else:
  4906. val = 0.1
  4907. try:
  4908. val = float(self.defaults[dim]) * sfactor
  4909. except Exception as e:
  4910. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4911. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  4912. else:
  4913. val = 0.1
  4914. if self.defaults[dim]:
  4915. try:
  4916. val = float(self.defaults[dim]) * sfactor
  4917. except Exception as e:
  4918. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4919. self.defaults[dim] = val
  4920. # The scaling factor depending on choice of units.
  4921. factor = 25.4 if new_units == 'MM' else 1/25.4
  4922. # Changing project units. Warn user.
  4923. msgbox = QtWidgets.QMessageBox()
  4924. msgbox.setWindowTitle(_("Toggle Units"))
  4925. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  4926. msgbox.setText(_("Changing the units of the project\n"
  4927. "will scale all objects.\n\n"
  4928. "Do you want to continue?"))
  4929. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4930. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4931. msgbox.setDefaultButton(bt_ok)
  4932. msgbox.exec_()
  4933. response = msgbox.clickedButton()
  4934. if response == bt_ok:
  4935. if no_pref is False:
  4936. self.defaults_read_form()
  4937. scale_defaults(factor)
  4938. self.defaults_write_form(fl_units=new_units)
  4939. self.defaults["units"] = new_units
  4940. # update the defaults from form, some may assume that the conversion is enough and it's not
  4941. self.on_options_app2project()
  4942. # update the objects
  4943. for obj in self.collection.get_list():
  4944. obj.convert_units(new_units)
  4945. # make that the properties stored in the object are also updated
  4946. self.object_changed.emit(obj)
  4947. # rebuild the object UI
  4948. obj.build_ui()
  4949. # change this only if the workspace is active
  4950. if self.defaults['global_workspace'] is True:
  4951. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  4952. # adjust the grid values on the main toolbar
  4953. val_x = float(self.defaults['global_gridx']) * factor
  4954. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  4955. current = self.collection.get_active()
  4956. if current is not None:
  4957. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4958. if not isinstance(current, FlatCAMGeometry):
  4959. current.to_form()
  4960. # replot all objects
  4961. self.plot_all()
  4962. # set the status labels to reflect the current FlatCAM units
  4963. self.set_screen_units(new_units)
  4964. # signal to the app that we changed the object properties and it shoud save the project
  4965. self.should_we_save = True
  4966. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  4967. else:
  4968. # Undo toggling
  4969. self.toggle_units_ignore = True
  4970. if self.defaults['units'].upper() == 'MM':
  4971. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4972. else:
  4973. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4974. self.toggle_units_ignore = False
  4975. # store the grid values so they are not changed in the next step
  4976. val_x = float(self.defaults['global_gridx'])
  4977. val_y = float(self.defaults['global_gridy'])
  4978. self.inform.emit('[WARNING_NOTCL]%s' % _("Units conversion cancelled."))
  4979. self.defaults_read_form()
  4980. # the self.defaults_read_form() will update all defaults values in self.defaults from the GUI elements but
  4981. # I don't want it for the grid values, so I update them here
  4982. self.defaults['global_gridx'] = val_x
  4983. self.defaults['global_gridy'] = val_y
  4984. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  4985. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  4986. def on_fullscreen(self, disable=False):
  4987. self.report_usage("on_fullscreen()")
  4988. if self.toggle_fscreen is False and disable is False:
  4989. # self.ui.showFullScreen()
  4990. self.ui.setWindowFlags(self.ui.windowFlags() | Qt.FramelessWindowHint)
  4991. a = self.ui.geometry()
  4992. self.x_pos = a.x()
  4993. self.y_pos = a.y()
  4994. self.width = a.width()
  4995. self.height = a.height()
  4996. # set new geometry to full desktop rect
  4997. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  4998. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  4999. # everything else will not work without this hack. This happen in Windows.
  5000. # https://bugreports.qt.io/browse/QTBUG-41309
  5001. desktop = QtWidgets.QApplication.desktop()
  5002. screen = desktop.screenNumber(QtGui.QCursor.pos())
  5003. rec = desktop.screenGeometry(screen)
  5004. x = rec.x() - 1
  5005. y = rec.y() - 1
  5006. h = rec.height() + 2
  5007. w = rec.width() + 2
  5008. self.ui.setGeometry(x, y, w, h)
  5009. self.ui.show()
  5010. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  5011. tb.setVisible(False)
  5012. self.ui.splitter_left.setVisible(False)
  5013. self.toggle_fscreen = True
  5014. elif self.toggle_fscreen is True or disable is True:
  5015. self.ui.setWindowFlags(self.ui.windowFlags() & ~Qt.FramelessWindowHint)
  5016. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  5017. self.ui.showNormal()
  5018. self.restore_toolbar_view()
  5019. self.ui.splitter_left.setVisible(True)
  5020. self.toggle_fscreen = False
  5021. def on_toggle_plotarea(self):
  5022. self.report_usage("on_toggle_plotarea()")
  5023. try:
  5024. name = self.ui.plot_tab_area.widget(0).objectName()
  5025. except AttributeError:
  5026. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  5027. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  5028. self.ui.plot_tab_area.protectTab(0)
  5029. return
  5030. if name != 'plotarea':
  5031. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5032. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  5033. self.ui.plot_tab_area.protectTab(0)
  5034. else:
  5035. self.ui.plot_tab_area.closeTab(0)
  5036. def on_toggle_notebook(self):
  5037. if self.ui.splitter.sizes()[0] == 0:
  5038. self.ui.splitter.setSizes([1, 1])
  5039. self.ui.menu_toggle_nb.setChecked(True)
  5040. else:
  5041. self.ui.splitter.setSizes([0, 1])
  5042. self.ui.menu_toggle_nb.setChecked(False)
  5043. def on_toggle_axis(self):
  5044. self.report_usage("on_toggle_axis()")
  5045. if self.toggle_axis is False:
  5046. if self.is_legacy is False:
  5047. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  5048. parent=self.plotcanvas.view.scene)
  5049. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  5050. parent=self.plotcanvas.view.scene)
  5051. else:
  5052. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  5053. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  5054. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  5055. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  5056. self.plotcanvas.canvas.draw()
  5057. self.toggle_axis = True
  5058. else:
  5059. if self.is_legacy is False:
  5060. self.plotcanvas.v_line.parent = None
  5061. self.plotcanvas.h_line.parent = None
  5062. else:
  5063. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  5064. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  5065. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  5066. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  5067. self.plotcanvas.canvas.draw()
  5068. self.toggle_axis = False
  5069. def on_toggle_grid(self):
  5070. self.report_usage("on_toggle_grid()")
  5071. self.ui.grid_snap_btn.trigger()
  5072. def on_toggle_grid_lines(self):
  5073. self.report_usage("on_toggle_grd_lines()")
  5074. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  5075. if tt_settings.contains("theme"):
  5076. theme = tt_settings.value('theme', type=str)
  5077. else:
  5078. theme = 'white'
  5079. if self.toggle_grid_lines is False:
  5080. if self.is_legacy is False:
  5081. if theme == 'white':
  5082. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  5083. else:
  5084. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  5085. else:
  5086. self.plotcanvas.axes.grid(True)
  5087. try:
  5088. self.plotcanvas.canvas.draw()
  5089. except IndexError:
  5090. pass
  5091. pass
  5092. self.toggle_grid_lines = True
  5093. else:
  5094. if self.is_legacy is False:
  5095. if theme == 'white':
  5096. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  5097. else:
  5098. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  5099. else:
  5100. self.plotcanvas.axes.grid(False)
  5101. try:
  5102. self.plotcanvas.canvas.draw()
  5103. except IndexError:
  5104. pass
  5105. self.toggle_grid_lines = False
  5106. if self.is_legacy is False:
  5107. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  5108. # - perhaps is a bug in VisPy implementation
  5109. if self.grid_status() is True:
  5110. self.app_cursor.enabled = False
  5111. self.app_cursor.enabled = True
  5112. else:
  5113. self.app_cursor.enabled = True
  5114. self.app_cursor.enabled = False
  5115. def show_preferences_gui(self):
  5116. """
  5117. Called to initialize and show the Preferences GUI
  5118. :return: None
  5119. """
  5120. self.gen_form = self.ui.general_defaults_form
  5121. self.ger_form = self.ui.gerber_defaults_form
  5122. self.exc_form = self.ui.excellon_defaults_form
  5123. self.geo_form = self.ui.geometry_defaults_form
  5124. self.cnc_form = self.ui.cncjob_defaults_form
  5125. self.tools_form = self.ui.tools_defaults_form
  5126. self.tools2_form = self.ui.tools2_defaults_form
  5127. self.fa_form = self.ui.util_defaults_form
  5128. try:
  5129. self.ui.general_scroll_area.takeWidget()
  5130. except Exception:
  5131. self.log.debug("Nothing to remove")
  5132. self.ui.general_scroll_area.setWidget(self.gen_form)
  5133. self.gen_form.show()
  5134. try:
  5135. self.ui.gerber_scroll_area.takeWidget()
  5136. except Exception:
  5137. self.log.debug("Nothing to remove")
  5138. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  5139. self.ger_form.show()
  5140. try:
  5141. self.ui.excellon_scroll_area.takeWidget()
  5142. except Exception:
  5143. self.log.debug("Nothing to remove")
  5144. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  5145. self.exc_form.show()
  5146. try:
  5147. self.ui.geometry_scroll_area.takeWidget()
  5148. except Exception:
  5149. self.log.debug("Nothing to remove")
  5150. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  5151. self.geo_form.show()
  5152. try:
  5153. self.ui.cncjob_scroll_area.takeWidget()
  5154. except Exception:
  5155. self.log.debug("Nothing to remove")
  5156. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  5157. self.cnc_form.show()
  5158. try:
  5159. self.ui.tools_scroll_area.takeWidget()
  5160. except Exception:
  5161. self.log.debug("Nothing to remove")
  5162. self.ui.tools_scroll_area.setWidget(self.tools_form)
  5163. self.tools_form.show()
  5164. try:
  5165. self.ui.tools2_scroll_area.takeWidget()
  5166. except Exception:
  5167. self.log.debug("Nothing to remove")
  5168. self.ui.tools2_scroll_area.setWidget(self.tools2_form)
  5169. self.tools2_form.show()
  5170. try:
  5171. self.ui.fa_scroll_area.takeWidget()
  5172. except Exception:
  5173. self.log.debug("Nothing to remove")
  5174. self.ui.fa_scroll_area.setWidget(self.fa_form)
  5175. self.fa_form.show()
  5176. self.log.debug("Finished Preferences GUI form initialization.")
  5177. # self.options2form()
  5178. def init_color_pickers_in_preferences_gui(self):
  5179. # Init Plot Colors
  5180. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  5181. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5182. "background-color:%s;"
  5183. "border-color: dimgray" % str(self.defaults['global_plot_fill'])[:7])
  5184. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  5185. int(self.defaults['global_plot_fill'][7:9], 16))
  5186. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  5187. int(self.defaults['global_plot_fill'][7:9], 16))
  5188. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  5189. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5190. "background-color:%s;"
  5191. "border-color: dimgray" % str(self.defaults['global_plot_line'])[:7])
  5192. # Init Left-Right Selection colors
  5193. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  5194. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5195. "background-color:%s;"
  5196. "border-color: dimgray" % str(self.defaults['global_sel_fill'])[:7])
  5197. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  5198. int(self.defaults['global_sel_fill'][7:9], 16))
  5199. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  5200. int(self.defaults['global_sel_fill'][7:9], 16))
  5201. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  5202. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5203. "background-color:%s;"
  5204. "border-color: dimgray" % str(self.defaults['global_sel_line'])[:7])
  5205. # Init Right-Left Selection colors
  5206. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  5207. self.defaults['global_alt_sel_fill'])
  5208. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5209. "background-color:%s;"
  5210. "border-color: dimgray" % str(self.defaults['global_alt_sel_fill'])[:7])
  5211. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  5212. int(self.defaults['global_sel_fill'][7:9], 16))
  5213. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  5214. int(self.defaults['global_sel_fill'][7:9], 16))
  5215. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  5216. self.defaults['global_alt_sel_line'])
  5217. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5218. "background-color:%s;"
  5219. "border-color: dimgray" % str(self.defaults['global_alt_sel_line'])[:7])
  5220. # Init Draw color and Selection Draw Color
  5221. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  5222. self.defaults['global_draw_color'])
  5223. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5224. "background-color:%s;"
  5225. "border-color: dimgray" % str(self.defaults['global_draw_color'])[:7])
  5226. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  5227. self.defaults['global_sel_draw_color'])
  5228. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5229. "background-color:%s;"
  5230. "border-color: dimgray" % str(self.defaults['global_sel_draw_color'])[:7])
  5231. # Init Project Items color
  5232. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  5233. self.defaults['global_proj_item_color'])
  5234. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5235. "background-color:%s;"
  5236. "border-color: dimgray" % str(self.defaults['global_proj_item_color'])[:7])
  5237. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  5238. self.defaults['global_proj_item_dis_color'])
  5239. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5240. "background-color:%s;"
  5241. "border-color: dimgray" % str(self.defaults['global_proj_item_dis_color'])[:7])
  5242. # Init the Annotation CNC Job color
  5243. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  5244. self.defaults['cncjob_annotation_fontcolor'])
  5245. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5246. "background-color:%s;"
  5247. "border-color: dimgray" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  5248. # Init the Tool Film color
  5249. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  5250. self.defaults['tools_film_color'])
  5251. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5252. "background-color:%s;"
  5253. "border-color: dimgray" % str(self.defaults['tools_film_color'])[:7]
  5254. )
  5255. # Init the Tool QRCode colors
  5256. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(
  5257. self.defaults['tools_qrcode_fill_color'])
  5258. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5259. "background-color:%s;"
  5260. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])[:7])
  5261. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(
  5262. self.defaults['tools_qrcode_back_color'])
  5263. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5264. "background-color:%s;"
  5265. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])[:7])
  5266. def on_excellon_defaults_button(self):
  5267. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  5268. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  5269. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  5270. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  5271. self.defaults_form_fields["excellon_zeros"].set_value('L')
  5272. self.defaults_form_fields["excellon_units"].set_value('INCH')
  5273. log.debug("Excellon app defaults loaded ...")
  5274. def on_update_exc_export(self, state):
  5275. """
  5276. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  5277. if the update_excellon_cb checkbox is checked
  5278. :param state: state of the checkbox whose signals is tied to his slot
  5279. :return:
  5280. """
  5281. if state:
  5282. # first try to disconnect
  5283. try:
  5284. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.\
  5285. disconnect(self.on_excellon_format_changed)
  5286. except TypeError:
  5287. pass
  5288. try:
  5289. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.\
  5290. disconnect(self.on_excellon_format_changed)
  5291. except TypeError:
  5292. pass
  5293. try:
  5294. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.\
  5295. disconnect(self.on_excellon_format_changed)
  5296. except TypeError:
  5297. pass
  5298. try:
  5299. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.\
  5300. disconnect(self.on_excellon_format_changed)
  5301. except TypeError:
  5302. pass
  5303. try:
  5304. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  5305. disconnect(self.on_excellon_zeros_changed)
  5306. except TypeError:
  5307. pass
  5308. try:
  5309. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  5310. disconnect(self.on_excellon_zeros_changed)
  5311. except TypeError:
  5312. pass
  5313. # the connect them
  5314. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  5315. self.on_excellon_format_changed)
  5316. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  5317. self.on_excellon_format_changed)
  5318. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  5319. self.on_excellon_format_changed)
  5320. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  5321. self.on_excellon_format_changed)
  5322. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  5323. self.on_excellon_zeros_changed)
  5324. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  5325. self.on_excellon_units_changed)
  5326. else:
  5327. # disconnect the signals
  5328. try:
  5329. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  5330. disconnect(self.on_excellon_format_changed)
  5331. except TypeError:
  5332. pass
  5333. try:
  5334. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  5335. disconnect(self.on_excellon_format_changed)
  5336. except TypeError:
  5337. pass
  5338. try:
  5339. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  5340. disconnect(self.on_excellon_format_changed)
  5341. except TypeError:
  5342. pass
  5343. try:
  5344. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  5345. disconnect(self.on_excellon_format_changed)
  5346. except TypeError:
  5347. pass
  5348. try:
  5349. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  5350. disconnect(self.on_excellon_zeros_changed)
  5351. except TypeError:
  5352. pass
  5353. try:
  5354. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  5355. disconnect(self.on_excellon_zeros_changed)
  5356. except TypeError:
  5357. pass
  5358. def on_excellon_format_changed(self):
  5359. """
  5360. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  5361. :return: None
  5362. """
  5363. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  5364. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5365. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  5366. )
  5367. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5368. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  5369. )
  5370. else:
  5371. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5372. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  5373. )
  5374. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5375. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  5376. )
  5377. def on_excellon_zeros_changed(self):
  5378. """
  5379. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  5380. :return: None
  5381. """
  5382. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  5383. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  5384. )
  5385. def on_excellon_units_changed(self):
  5386. """
  5387. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  5388. :return: None
  5389. """
  5390. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  5391. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  5392. )
  5393. self.on_excellon_format_changed()
  5394. # Setting plot colors handlers
  5395. def on_pf_color_entry(self):
  5396. self.defaults['global_plot_fill'] = \
  5397. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  5398. self.defaults['global_plot_fill'][7:9]
  5399. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5400. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  5401. def on_pf_color_button(self):
  5402. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  5403. c_dialog = QtWidgets.QColorDialog()
  5404. plot_fill_color = c_dialog.getColor(initial=current_color)
  5405. if plot_fill_color.isValid() is False:
  5406. return
  5407. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  5408. "background-color:%s" % str(plot_fill_color.name()))
  5409. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  5410. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  5411. self.defaults['global_plot_fill'] = new_val
  5412. def on_pf_color_spinner(self):
  5413. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  5414. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  5415. self.defaults['global_plot_fill'] = \
  5416. self.defaults['global_plot_fill'][:7] + \
  5417. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5418. self.defaults['global_plot_line'] = \
  5419. self.defaults['global_plot_line'][:7] + \
  5420. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5421. def on_pf_color_slider(self):
  5422. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  5423. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  5424. def on_pl_color_entry(self):
  5425. self.defaults['global_plot_line'] = \
  5426. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  5427. self.defaults['global_plot_line'][7:9]
  5428. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5429. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  5430. def on_pl_color_button(self):
  5431. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  5432. # print(current_color)
  5433. c_dialog = QtWidgets.QColorDialog()
  5434. plot_line_color = c_dialog.getColor(initial=current_color)
  5435. if plot_line_color.isValid() is False:
  5436. return
  5437. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  5438. "background-color:%s" % str(plot_line_color.name()))
  5439. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  5440. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  5441. self.defaults['global_plot_line'] = new_val_line
  5442. # Setting selection colors (left - right) handlers
  5443. def on_sf_color_entry(self):
  5444. self.defaults['global_sel_fill'] = \
  5445. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  5446. self.defaults['global_sel_fill'][7:9]
  5447. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5448. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  5449. def on_sf_color_button(self):
  5450. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  5451. c_dialog = QtWidgets.QColorDialog()
  5452. plot_fill_color = c_dialog.getColor(initial=current_color)
  5453. if plot_fill_color.isValid() is False:
  5454. return
  5455. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5456. "background-color:%s" % str(plot_fill_color.name()))
  5457. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  5458. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  5459. self.defaults['global_sel_fill'] = new_val
  5460. def on_sf_color_spinner(self):
  5461. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  5462. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  5463. self.defaults['global_sel_fill'] = \
  5464. self.defaults['global_sel_fill'][:7] + \
  5465. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5466. self.defaults['global_sel_line'] = \
  5467. self.defaults['global_sel_line'][:7] + \
  5468. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5469. def on_sf_color_slider(self):
  5470. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  5471. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  5472. def on_sl_color_entry(self):
  5473. self.defaults['global_sel_line'] = \
  5474. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  5475. self.defaults['global_sel_line'][7:9]
  5476. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5477. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  5478. def on_sl_color_button(self):
  5479. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  5480. c_dialog = QtWidgets.QColorDialog()
  5481. plot_line_color = c_dialog.getColor(initial=current_color)
  5482. if plot_line_color.isValid() is False:
  5483. return
  5484. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5485. "background-color:%s" % str(plot_line_color.name()))
  5486. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  5487. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  5488. self.defaults['global_sel_line'] = new_val_line
  5489. # Setting selection colors (right - left) handlers
  5490. def on_alt_sf_color_entry(self):
  5491. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  5492. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  5493. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5494. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  5495. def on_alt_sf_color_button(self):
  5496. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  5497. c_dialog = QtWidgets.QColorDialog()
  5498. plot_fill_color = c_dialog.getColor(initial=current_color)
  5499. if plot_fill_color.isValid() is False:
  5500. return
  5501. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5502. "background-color:%s" % str(plot_fill_color.name()))
  5503. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  5504. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  5505. self.defaults['global_alt_sel_fill'] = new_val
  5506. def on_alt_sf_color_spinner(self):
  5507. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  5508. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  5509. self.defaults['global_alt_sel_fill'] = \
  5510. self.defaults['global_alt_sel_fill'][:7] + \
  5511. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5512. self.defaults['global_alt_sel_line'] = \
  5513. self.defaults['global_alt_sel_line'][:7] + \
  5514. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5515. def on_alt_sf_color_slider(self):
  5516. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  5517. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  5518. def on_alt_sl_color_entry(self):
  5519. self.defaults['global_alt_sel_line'] = \
  5520. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  5521. self.defaults['global_alt_sel_line'][7:9]
  5522. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5523. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  5524. def on_alt_sl_color_button(self):
  5525. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  5526. c_dialog = QtWidgets.QColorDialog()
  5527. plot_line_color = c_dialog.getColor(initial=current_color)
  5528. if plot_line_color.isValid() is False:
  5529. return
  5530. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5531. "background-color:%s" % str(plot_line_color.name()))
  5532. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  5533. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  5534. self.defaults['global_alt_sel_line'] = new_val_line
  5535. # Setting Editor colors
  5536. def on_draw_color_entry(self):
  5537. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5538. .draw_color_entry.get_value()
  5539. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5540. "background-color:%s" % str(self.defaults['global_draw_color']))
  5541. def on_draw_color_button(self):
  5542. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  5543. c_dialog = QtWidgets.QColorDialog()
  5544. draw_color = c_dialog.getColor(initial=current_color)
  5545. if draw_color.isValid() is False:
  5546. return
  5547. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5548. "background-color:%s" % str(draw_color.name()))
  5549. new_val = str(draw_color.name())
  5550. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  5551. self.defaults['global_draw_color'] = new_val
  5552. def on_sel_draw_color_entry(self):
  5553. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5554. .sel_draw_color_entry.get_value()
  5555. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5556. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  5557. def on_sel_draw_color_button(self):
  5558. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  5559. c_dialog = QtWidgets.QColorDialog()
  5560. sel_draw_color = c_dialog.getColor(initial=current_color)
  5561. if sel_draw_color.isValid() is False:
  5562. return
  5563. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5564. "background-color:%s" % str(sel_draw_color.name()))
  5565. new_val_sel = str(sel_draw_color.name())
  5566. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  5567. self.defaults['global_sel_draw_color'] = new_val_sel
  5568. def on_proj_color_entry(self):
  5569. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  5570. .proj_color_entry.get_value()
  5571. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5572. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  5573. def on_proj_color_button(self):
  5574. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  5575. c_dialog = QtWidgets.QColorDialog()
  5576. proj_color = c_dialog.getColor(initial=current_color)
  5577. if proj_color.isValid() is False:
  5578. return
  5579. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5580. "background-color:%s" % str(proj_color.name()))
  5581. new_val_sel = str(proj_color.name())
  5582. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5583. self.defaults['global_proj_item_color'] = new_val_sel
  5584. def on_proj_color_dis_entry(self):
  5585. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5586. .proj_color_dis_entry.get_value()
  5587. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5588. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5589. def on_proj_color_dis_button(self):
  5590. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5591. c_dialog = QtWidgets.QColorDialog()
  5592. proj_color = c_dialog.getColor(initial=current_color)
  5593. if proj_color.isValid() is False:
  5594. return
  5595. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5596. "background-color:%s" % str(proj_color.name()))
  5597. new_val_sel = str(proj_color.name())
  5598. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5599. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5600. def on_annotation_fontcolor_entry(self):
  5601. self.defaults['cncjob_annotation_fontcolor'] = \
  5602. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5603. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5604. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5605. def on_annotation_fontcolor_button(self):
  5606. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5607. c_dialog = QtWidgets.QColorDialog()
  5608. annotation_color = c_dialog.getColor(initial=current_color)
  5609. if annotation_color.isValid() is False:
  5610. return
  5611. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5612. "background-color:%s" % str(annotation_color.name()))
  5613. new_val_sel = str(annotation_color.name())
  5614. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5615. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5616. def on_film_color_entry(self):
  5617. self.defaults['tools_film_color'] = \
  5618. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5619. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5620. "background-color:%s;"
  5621. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  5622. )
  5623. def on_film_color_button(self):
  5624. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5625. c_dialog = QtWidgets.QColorDialog()
  5626. film_color = c_dialog.getColor(initial=current_color)
  5627. if film_color.isValid() is False:
  5628. return
  5629. # if new color is different then mark that the Preferences are changed
  5630. if film_color != current_color:
  5631. self.on_preferences_edited()
  5632. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5633. "background-color:%s;"
  5634. "border-color: dimgray" % str(film_color.name())
  5635. )
  5636. new_val_sel = str(film_color.name())
  5637. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5638. self.defaults['tools_film_color'] = new_val_sel
  5639. def on_qrcode_fill_color_entry(self):
  5640. self.defaults['tools_qrcode_fill_color'] = \
  5641. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  5642. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5643. "background-color:%s;"
  5644. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  5645. )
  5646. def on_qrcode_fill_color_button(self):
  5647. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  5648. c_dialog = QtWidgets.QColorDialog()
  5649. fill_color = c_dialog.getColor(initial=current_color)
  5650. if fill_color.isValid() is False:
  5651. return
  5652. # if new color is different then mark that the Preferences are changed
  5653. if fill_color != current_color:
  5654. self.on_preferences_edited()
  5655. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5656. "background-color:%s;"
  5657. "border-color: dimgray" % str(fill_color.name())
  5658. )
  5659. new_val_sel = str(fill_color.name())
  5660. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  5661. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  5662. def on_qrcode_back_color_entry(self):
  5663. self.defaults['tools_qrcode_back_color'] = \
  5664. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  5665. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5666. "background-color:%s;"
  5667. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  5668. )
  5669. def on_qrcode_back_color_button(self):
  5670. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  5671. c_dialog = QtWidgets.QColorDialog()
  5672. back_color = c_dialog.getColor(initial=current_color)
  5673. if back_color.isValid() is False:
  5674. return
  5675. # if new color is different then mark that the Preferences are changed
  5676. if back_color != current_color:
  5677. self.on_preferences_edited()
  5678. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5679. "background-color:%s;"
  5680. "border-color: dimgray" % str(back_color.name())
  5681. )
  5682. new_val_sel = str(back_color.name())
  5683. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  5684. self.defaults['tools_qrcode_back_color'] = new_val_sel
  5685. def on_splash_changed(self, state):
  5686. settings = QSettings("Open Source", "FlatCAM")
  5687. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5688. # This will write the setting to the platform specific storage.
  5689. del settings
  5690. def on_tab_rmb_click(self, checked):
  5691. self.ui.notebook.set_detachable(val=checked)
  5692. self.defaults["global_tabs_detachable"] = checked
  5693. self.ui.plot_tab_area.set_detachable(val=checked)
  5694. self.defaults["global_tabs_detachable"] = checked
  5695. def on_tab_setup_context_menu(self):
  5696. initial_checked = self.defaults["global_tabs_detachable"]
  5697. action_name = str(_("Detachable Tabs"))
  5698. action = QtWidgets.QAction(self)
  5699. action.setCheckable(True)
  5700. action.setText(action_name)
  5701. action.setChecked(initial_checked)
  5702. self.ui.notebook.tabBar.addAction(action)
  5703. self.ui.plot_tab_area.tabBar.addAction(action)
  5704. try:
  5705. action.triggered.disconnect()
  5706. except TypeError:
  5707. pass
  5708. action.triggered.connect(self.on_tab_rmb_click)
  5709. def on_deselect_all(self):
  5710. self.collection.set_all_inactive()
  5711. self.delete_selection_shape()
  5712. def on_workspace_modified(self):
  5713. # self.save_defaults(silent=True)
  5714. if self.is_legacy is True:
  5715. self.plotcanvas.delete_workspace()
  5716. self.defaults_read_form()
  5717. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5718. def on_workspace(self):
  5719. if self.ui.general_defaults_form.general_gui_group.workspace_cb.get_value():
  5720. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5721. else:
  5722. self.plotcanvas.delete_workspace()
  5723. self.defaults_read_form()
  5724. # self.save_defaults(silent=True)
  5725. def on_workspace_toggle(self):
  5726. state = False if self.ui.general_defaults_form.general_gui_group.workspace_cb.get_value() else True
  5727. try:
  5728. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  5729. except TypeError:
  5730. pass
  5731. self.ui.general_defaults_form.general_gui_group.workspace_cb.set_value(state)
  5732. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  5733. self.on_workspace()
  5734. def on_layout(self, index=None, lay=None):
  5735. """
  5736. Set the toolbars layout (location)
  5737. :param index:
  5738. :param lay: type of layout to be set on the toolbard
  5739. :return: None
  5740. """
  5741. self.report_usage("on_layout()")
  5742. if lay:
  5743. current_layout = lay
  5744. else:
  5745. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5746. lay_settings = QSettings("Open Source", "FlatCAM")
  5747. lay_settings.setValue('layout', current_layout)
  5748. # This will write the setting to the platform specific storage.
  5749. del lay_settings
  5750. # first remove the toolbars:
  5751. try:
  5752. self.ui.removeToolBar(self.ui.toolbarfile)
  5753. self.ui.removeToolBar(self.ui.toolbargeo)
  5754. self.ui.removeToolBar(self.ui.toolbarview)
  5755. self.ui.removeToolBar(self.ui.toolbarshell)
  5756. self.ui.removeToolBar(self.ui.toolbartools)
  5757. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5758. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5759. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5760. self.ui.removeToolBar(self.ui.snap_toolbar)
  5761. self.ui.removeToolBar(self.ui.toolbarshell)
  5762. except Exception:
  5763. pass
  5764. if current_layout == 'standard':
  5765. # ## TOOLBAR INSTALLATION # ##
  5766. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5767. self.ui.toolbarfile.setObjectName('File_TB')
  5768. self.ui.addToolBar(self.ui.toolbarfile)
  5769. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5770. self.ui.toolbargeo.setObjectName('Edit_TB')
  5771. self.ui.addToolBar(self.ui.toolbargeo)
  5772. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5773. self.ui.toolbarview.setObjectName('View_TB')
  5774. self.ui.addToolBar(self.ui.toolbarview)
  5775. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5776. self.ui.toolbarshell.setObjectName('Shell_TB')
  5777. self.ui.addToolBar(self.ui.toolbarshell)
  5778. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5779. self.ui.toolbartools.setObjectName('Tools_TB')
  5780. self.ui.addToolBar(self.ui.toolbartools)
  5781. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5782. # self.ui.exc_edit_toolbar.setVisible(False)
  5783. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5784. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5785. self.ui.addToolBarBreak()
  5786. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5787. # self.ui.geo_edit_toolbar.setVisible(False)
  5788. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5789. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5790. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5791. # self.ui.grb_edit_toolbar.setVisible(False)
  5792. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5793. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5794. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5795. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5796. # self.ui.snap_toolbar.setMaximumHeight(30)
  5797. self.ui.addToolBar(self.ui.snap_toolbar)
  5798. self.ui.corner_snap_btn.setVisible(False)
  5799. self.ui.snap_magnet.setVisible(False)
  5800. elif current_layout == 'compact':
  5801. # ## TOOLBAR INSTALLATION # ##
  5802. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5803. self.ui.toolbarfile.setObjectName('File_TB')
  5804. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5805. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5806. self.ui.toolbargeo.setObjectName('Edit_TB')
  5807. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5808. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5809. self.ui.toolbarshell.setObjectName('Shell_TB')
  5810. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5811. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5812. self.ui.toolbartools.setObjectName('Tools_TB')
  5813. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5814. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5815. # self.ui.geo_edit_toolbar.setVisible(False)
  5816. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5817. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5818. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5819. self.ui.toolbarview.setObjectName('View_TB')
  5820. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5821. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5822. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5823. # self.ui.grb_edit_toolbar.setVisible(False)
  5824. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5825. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5826. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5827. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5828. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5829. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5830. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5831. self.ui.snap_toolbar.setMaximumHeight(30)
  5832. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5833. self.ui.corner_snap_btn.setVisible(True)
  5834. self.ui.snap_magnet.setVisible(True)
  5835. # add all the actions to the toolbars
  5836. self.ui.populate_toolbars()
  5837. # reconnect all the signals to the toolbar actions
  5838. self.connect_toolbar_signals()
  5839. self.ui.grid_snap_btn.setChecked(True)
  5840. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5841. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5842. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5843. self.ui.grid_gap_link_cb.setChecked(True)
  5844. def on_cursor_type(self, val):
  5845. """
  5846. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  5847. :return: None
  5848. """
  5849. self.app_cursor.enabled = False
  5850. if val == 'small':
  5851. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(False)
  5852. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(False)
  5853. self.app_cursor = self.plotcanvas.new_cursor()
  5854. else:
  5855. self.ui.general_defaults_form.general_gui_set_group.cursor_size_entry.setDisabled(True)
  5856. self.ui.general_defaults_form.general_gui_set_group.cursor_size_lbl.setDisabled(True)
  5857. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  5858. if self.ui.grid_snap_btn.isChecked():
  5859. self.app_cursor.enabled = True
  5860. else:
  5861. self.app_cursor.enabled = False
  5862. def on_cnc_custom_parameters(self, signal_text):
  5863. if signal_text == 'Parameters':
  5864. return
  5865. else:
  5866. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5867. def on_save_button(self, save_to_file=True):
  5868. log.debug("App.on_save_button() --> Applying preferences to file.")
  5869. # Preferences saved, update flag
  5870. self.preferences_changed_flag = False
  5871. # Preferences save, update the color of the Preferences Tab text
  5872. for idx in range(self.ui.plot_tab_area.count()):
  5873. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5874. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5875. self.inform.emit('%s' % _("Preferences applied."))
  5876. if save_to_file:
  5877. self.save_defaults(silent=False)
  5878. # load the defaults so they are updated into the app
  5879. self.load_defaults(filename='current_defaults')
  5880. # Re-fresh project options
  5881. self.on_options_app2project()
  5882. settgs = QSettings("Open Source", "FlatCAM")
  5883. # save the notebook font size
  5884. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5885. settgs.setValue('notebook_font_size', fsize)
  5886. # save the axis font size
  5887. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5888. settgs.setValue('axis_font_size', g_fsize)
  5889. # save the textbox font size
  5890. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5891. settgs.setValue('textbox_font_size', tb_fsize)
  5892. settgs.setValue(
  5893. 'machinist',
  5894. 1 if self.ui.general_defaults_form.general_app_group.machinist_cb.get_value() else 0
  5895. )
  5896. # This will write the setting to the platform specific storage.
  5897. del settgs
  5898. def on_pref_close_button(self):
  5899. # Preferences saved, update flag
  5900. self.preferences_changed_flag = False
  5901. try:
  5902. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_plot_area_tab_closed)
  5903. except TypeError:
  5904. pass
  5905. self.defaults_write_form()
  5906. # Preferences save, update the color of the Preferences Tab text
  5907. for idx in range(self.ui.plot_tab_area.count()):
  5908. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5909. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5910. self.ui.plot_tab_area.closeTab(idx)
  5911. break
  5912. self.inform.emit('%s' % _("Preferences closed without saving."))
  5913. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  5914. def on_tool_add_keypress(self):
  5915. # ## Current application units in Upper Case
  5916. self.units = self.defaults['units'].upper()
  5917. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5918. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5919. if notebook_widget_name == 'selected_tab':
  5920. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5921. # Tool add works for Geometry only if Advanced is True in Preferences
  5922. if self.defaults["global_app_level"] == 'a':
  5923. tool_add_popup = FCInputDialog(title="New Tool ...",
  5924. text='Enter a Tool Diameter:',
  5925. min=0.0000, max=99.9999, decimals=4)
  5926. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  5927. val, ok = tool_add_popup.get_value()
  5928. if ok:
  5929. if float(val) == 0:
  5930. self.inform.emit('[WARNING_NOTCL] %s' %
  5931. _("Please enter a tool diameter with non-zero value, in Float format."))
  5932. return
  5933. self.collection.get_active().on_tool_add(dia=float(val))
  5934. else:
  5935. self.inform.emit('[WARNING_NOTCL] %s...' %
  5936. _("Adding Tool cancelled"))
  5937. else:
  5938. msgbox = QtWidgets.QMessageBox()
  5939. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5940. "Go to Preferences -> General - Show Advanced Options."))
  5941. msgbox.setWindowTitle("Tool adding ...")
  5942. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  5943. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5944. msgbox.setDefaultButton(bt_ok)
  5945. msgbox.exec_()
  5946. # work only if the notebook tab on focus is the Tools_Tab
  5947. if notebook_widget_name == 'tool_tab':
  5948. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5949. # and only if the tool is NCC Tool
  5950. if tool_widget == self.ncclear_tool.toolName:
  5951. self.ncclear_tool.on_add_tool_by_key()
  5952. # and only if the tool is Paint Area Tool
  5953. elif tool_widget == self.paint_tool.toolName:
  5954. self.paint_tool.on_add_tool_by_key()
  5955. # and only if the tool is Solder Paste Dispensing Tool
  5956. elif tool_widget == self.paste_tool.toolName:
  5957. self.paste_tool.on_add_tool_by_key()
  5958. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5959. # See description bellow.
  5960. def on_delete_keypress(self):
  5961. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5962. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5963. if notebook_widget_name == 'selected_tab':
  5964. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5965. self.collection.get_active().on_tool_delete()
  5966. # work only if the notebook tab on focus is the Tools_Tab
  5967. elif notebook_widget_name == 'tool_tab':
  5968. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5969. # and only if the tool is NCC Tool
  5970. if tool_widget == self.ncclear_tool.toolName:
  5971. self.ncclear_tool.on_tool_delete()
  5972. # and only if the tool is Paint Tool
  5973. elif tool_widget == self.paint_tool.toolName:
  5974. self.paint_tool.on_tool_delete()
  5975. # and only if the tool is Solder Paste Dispensing Tool
  5976. elif tool_widget == self.paste_tool.toolName:
  5977. self.paste_tool.on_tool_delete()
  5978. else:
  5979. self.on_delete()
  5980. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5981. # some screens you have to be careful where you hover with your mouse.
  5982. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5983. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5984. # Complicated, I know :)
  5985. def on_delete(self):
  5986. """
  5987. Delete the currently selected FlatCAMObjs.
  5988. :return: None
  5989. """
  5990. self.report_usage("on_delete()")
  5991. response = None
  5992. bt_ok = None
  5993. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5994. # a geometry object before we update it.
  5995. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5996. and self.grb_editor.editor_active is False:
  5997. if self.defaults["global_delete_confirmation"] is True:
  5998. msgbox = QtWidgets.QMessageBox()
  5999. msgbox.setWindowTitle(_("Delete objects"))
  6000. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  6001. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  6002. msgbox.setText(_("Are you sure you want to permanently delete\n"
  6003. "the selected objects?"))
  6004. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6005. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6006. msgbox.setDefaultButton(bt_ok)
  6007. msgbox.exec_()
  6008. response = msgbox.clickedButton()
  6009. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  6010. if self.collection.get_active():
  6011. self.log.debug("App.on_delete()")
  6012. while self.collection.get_active():
  6013. obj_active = self.collection.get_active()
  6014. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  6015. if isinstance(obj_active, FlatCAMGerber):
  6016. for el in obj_active.mark_shapes:
  6017. obj_active.mark_shapes[el].clear(update=True)
  6018. obj_active.mark_shapes[el].enabled = False
  6019. # obj_active.mark_shapes[el] = None
  6020. del el
  6021. elif isinstance(obj_active, FlatCAMCNCjob):
  6022. try:
  6023. obj_active.annotation.clear(update=True)
  6024. obj_active.annotation.enabled = False
  6025. except AttributeError:
  6026. pass
  6027. self.delete_first_selected()
  6028. self.inform.emit('%s...' %
  6029. _("Object(s) deleted"))
  6030. # make sure that the selection shape is deleted, too
  6031. self.delete_selection_shape()
  6032. else:
  6033. self.inform.emit(_("Failed. No object(s) selected..."))
  6034. else:
  6035. self.inform.emit(_("Save the work in Editor and try again ..."))
  6036. def delete_first_selected(self):
  6037. # Keep this for later
  6038. try:
  6039. sel_obj = self.collection.get_active()
  6040. name = sel_obj.options["name"]
  6041. isPlotted = sel_obj.options["plot"]
  6042. except AttributeError:
  6043. self.log.debug("Nothing selected for deletion")
  6044. return
  6045. if self.is_legacy is True:
  6046. # Remove plot only if the object was plotted otherwise delaxes will fail
  6047. if isPlotted:
  6048. try:
  6049. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  6050. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  6051. except Exception as e:
  6052. log.debug("App.delete_first_selected() --> %s" % str(e))
  6053. self.plotcanvas.auto_adjust_axes()
  6054. # Remove from dictionary
  6055. self.collection.delete_active()
  6056. # Clear form
  6057. self.setup_component_editor()
  6058. self.inform.emit('%s: %s' %
  6059. (_("Object deleted"), name))
  6060. def on_set_origin(self):
  6061. """
  6062. Set the origin to the left mouse click position
  6063. :return: None
  6064. """
  6065. # display the message for the user
  6066. # and ask him to click on the desired position
  6067. self.report_usage("on_set_origin()")
  6068. def origin_replot():
  6069. def worker_task():
  6070. with self.proc_container.new('%s...' % _("Plotting")):
  6071. for obj in self.collection.get_list():
  6072. obj.plot()
  6073. self.plotcanvas.fit_view()
  6074. if self.is_legacy:
  6075. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  6076. else:
  6077. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  6078. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6079. self.inform.emit(_('Click to set the origin ...'))
  6080. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  6081. # first disconnect it as it may have been used by something else
  6082. try:
  6083. self.replot_signal.disconnect()
  6084. except TypeError:
  6085. pass
  6086. self.replot_signal[list].connect(origin_replot)
  6087. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  6088. """
  6089. :param event:
  6090. :param location:
  6091. :param noplot:
  6092. :param use_thread:
  6093. :return:
  6094. """
  6095. noplot_sig = noplot
  6096. def worker_task():
  6097. with self.proc_container.new(_("Setting Origin...")):
  6098. for obj in self.collection.get_list():
  6099. obj.offset((x, y))
  6100. self.object_changed.emit(obj)
  6101. # Update the object bounding box options
  6102. a, b, c, d = obj.bounds()
  6103. obj.options['xmin'] = a
  6104. obj.options['ymin'] = b
  6105. obj.options['xmax'] = c
  6106. obj.options['ymax'] = d
  6107. self.inform.emit('[success] %s...' %
  6108. _('Origin set'))
  6109. if noplot_sig is False:
  6110. self.replot_signal.emit([])
  6111. if location is not None:
  6112. if len(location) != 2:
  6113. self.inform.emit('[ERROR_NOTCL] %s...' %
  6114. _("Origin coordinates specified but incomplete."))
  6115. return 'fail'
  6116. x, y = location
  6117. if use_thread is True:
  6118. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6119. else:
  6120. worker_task()
  6121. self.should_we_save = True
  6122. return
  6123. if event.button == 1:
  6124. if self.is_legacy is False:
  6125. event_pos = event.pos
  6126. else:
  6127. event_pos = (event.xdata, event.ydata)
  6128. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6129. if self.grid_status() == True:
  6130. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6131. else:
  6132. pos = pos_canvas
  6133. x = 0 - pos[0]
  6134. y = 0 - pos[1]
  6135. if use_thread is True:
  6136. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6137. else:
  6138. worker_task()
  6139. self.should_we_save = True
  6140. def on_jump_to(self, custom_location=None, fit_center=True):
  6141. """
  6142. Jump to a location by setting the mouse cursor location
  6143. :return:
  6144. """
  6145. self.report_usage("on_jump_to()")
  6146. # if self.is_legacy is True:
  6147. # self.inform.emit(_("Not available with the current Graphic Engine Legacy(2D)."))
  6148. # return
  6149. if not custom_location:
  6150. dia_box_location = None
  6151. try:
  6152. dia_box_location = eval(self.clipboard.text())
  6153. except Exception:
  6154. pass
  6155. if type(dia_box_location) == tuple:
  6156. dia_box_location = str(dia_box_location)
  6157. else:
  6158. dia_box_location = None
  6159. dia_box = Dialog_box(title=_("Jump to ..."),
  6160. label=_("Enter the coordinates in format X,Y:"),
  6161. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6162. initial_text=dia_box_location)
  6163. if dia_box.ok is True:
  6164. try:
  6165. location = eval(dia_box.location)
  6166. if not isinstance(location, tuple):
  6167. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  6168. return
  6169. except Exception:
  6170. return
  6171. else:
  6172. return
  6173. else:
  6174. location = custom_location
  6175. units = self.defaults['units'].upper()
  6176. if fit_center:
  6177. self.plotcanvas.fit_center(loc=location)
  6178. cursor = QtGui.QCursor()
  6179. if self.is_legacy is False:
  6180. # I don't know where those differences come from but they are constant for the current
  6181. # execution of the application and they are multiples of a value around 0.0263mm.
  6182. # In a random way sometimes they are more sometimes they are less
  6183. # if units == 'MM':
  6184. # cal_factor = 0.0263
  6185. # else:
  6186. # cal_factor = 0.0263 / 25.4
  6187. cal_location = (location[0], location[1])
  6188. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6189. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  6190. j_pos = (
  6191. int(canvas_origin.x() + round(jump_loc[0])),
  6192. int(canvas_origin.y() + round(jump_loc[1]))
  6193. )
  6194. cursor.setPos(j_pos[0], j_pos[1])
  6195. else:
  6196. # find the canvas origin which is in the top left corner
  6197. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6198. # determine the coordinates for the lowest left point of the canvas
  6199. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  6200. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  6201. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  6202. # canvas) and the point (width, height) is in the top-right location
  6203. loc = self.plotcanvas.axes.transData.transform_point(location)
  6204. j_pos = (
  6205. int(x0 + loc[0]),
  6206. int(y0 - loc[1])
  6207. )
  6208. cursor.setPos(j_pos[0], j_pos[1])
  6209. self.plotcanvas.mouse = [location[0], location[1]]
  6210. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  6211. if self.grid_status():
  6212. # Update cursor
  6213. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  6214. symbol='++', edge_color=self.cursor_color_3D,
  6215. size=self.defaults["global_cursor_size"])
  6216. # Set the position label
  6217. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6218. "<b>Y</b>: %.4f" % (location[0], location[1]))
  6219. # Set the relative position label
  6220. dx = location[0] - float(self.rel_point1[0])
  6221. dy = location[1] - float(self.rel_point1[1])
  6222. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6223. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6224. self.inform.emit('[success] %s' % _("Done."))
  6225. return location
  6226. def on_copy_object(self):
  6227. self.report_usage("on_copy_object()")
  6228. def initialize(obj_init, app):
  6229. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6230. try:
  6231. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6232. except AttributeError:
  6233. pass
  6234. try:
  6235. obj_init.apertures = deepcopy(obj.apertures)
  6236. except AttributeError:
  6237. pass
  6238. try:
  6239. if obj.tools:
  6240. obj_init.tools = deepcopy(obj.tools)
  6241. except Exception as e:
  6242. log.debug("App.on_copy_object() --> %s" % str(e))
  6243. try:
  6244. obj_init.source_file = deepcopy(obj.source_file)
  6245. except (AttributeError, TypeError):
  6246. pass
  6247. def initialize_excellon(obj_init, app):
  6248. obj_init.source_file = deepcopy(obj.source_file)
  6249. obj_init.tools = deepcopy(obj.tools)
  6250. # drills are offset, so they need to be deep copied
  6251. obj_init.drills = deepcopy(obj.drills)
  6252. # slots are offset, so they need to be deep copied
  6253. obj_init.slots = deepcopy(obj.slots)
  6254. obj_init.create_geometry()
  6255. def initialize_script(obj_init, app_obj):
  6256. obj_init.source_file = deepcopy(obj.source_file)
  6257. def initialize_document(obj_init, app_obj):
  6258. obj_init.source_file = deepcopy(obj.source_file)
  6259. for obj in self.collection.get_selected():
  6260. obj_name = obj.options["name"]
  6261. try:
  6262. if isinstance(obj, FlatCAMExcellon):
  6263. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  6264. elif isinstance(obj, FlatCAMGerber):
  6265. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  6266. elif isinstance(obj, FlatCAMGeometry):
  6267. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  6268. elif isinstance(obj, FlatCAMScript):
  6269. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  6270. elif isinstance(obj, FlatCAMDocument):
  6271. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  6272. except Exception as e:
  6273. return "Operation failed: %s" % str(e)
  6274. def on_copy_object2(self, custom_name):
  6275. def initialize_geometry(obj_init, app):
  6276. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6277. try:
  6278. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6279. except AttributeError:
  6280. pass
  6281. try:
  6282. obj_init.apertures = deepcopy(obj.apertures)
  6283. except AttributeError:
  6284. pass
  6285. try:
  6286. if obj.tools:
  6287. obj_init.tools = deepcopy(obj.tools)
  6288. except Exception as ee:
  6289. log.debug("on_copy_object2() --> %s" % str(ee))
  6290. def initialize_gerber(obj_init, app):
  6291. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6292. obj_init.apertures = deepcopy(obj.apertures)
  6293. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  6294. def initialize_excellon(obj_init, app):
  6295. obj_init.tools = deepcopy(obj.tools)
  6296. # drills are offset, so they need to be deep copied
  6297. obj_init.drills = deepcopy(obj.drills)
  6298. # slots are offset, so they need to be deep copied
  6299. obj_init.slots = deepcopy(obj.slots)
  6300. obj_init.create_geometry()
  6301. for obj in self.collection.get_selected():
  6302. obj_name = obj.options["name"]
  6303. try:
  6304. if isinstance(obj, FlatCAMExcellon):
  6305. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  6306. elif isinstance(obj, FlatCAMGerber):
  6307. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  6308. elif isinstance(obj, FlatCAMGeometry):
  6309. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  6310. except Exception as e:
  6311. return "Operation failed: %s" % str(e)
  6312. def on_rename_object(self, text):
  6313. self.report_usage("on_rename_object()")
  6314. named_obj = self.collection.get_active()
  6315. for obj in named_obj:
  6316. if obj is list:
  6317. self.on_rename_object(text)
  6318. else:
  6319. try:
  6320. obj.options['name'] = text
  6321. except Exception as e:
  6322. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  6323. def convert_any2geo(self):
  6324. self.report_usage("convert_any2geo()")
  6325. def initialize(obj_init, app):
  6326. obj_init.solid_geometry = obj.solid_geometry
  6327. try:
  6328. obj_init.follow_geometry = obj.follow_geometry
  6329. except AttributeError:
  6330. pass
  6331. try:
  6332. obj_init.apertures = obj.apertures
  6333. except AttributeError:
  6334. pass
  6335. try:
  6336. if obj.tools:
  6337. obj_init.tools = obj.tools
  6338. except AttributeError:
  6339. pass
  6340. def initialize_excellon(obj_init, app):
  6341. # objs = self.collection.get_selected()
  6342. # FlatCAMGeometry.merge(objs, obj)
  6343. solid_geo = []
  6344. for tool in obj.tools:
  6345. for geo in obj.tools[tool]['solid_geometry']:
  6346. solid_geo.append(geo)
  6347. obj_init.solid_geometry = deepcopy(solid_geo)
  6348. if not self.collection.get_selected():
  6349. log.warning("App.convert_any2geo --> No object selected")
  6350. self.inform.emit('[WARNING_NOTCL] %s' %
  6351. _("No object is selected. Select an object and try again."))
  6352. return
  6353. for obj in self.collection.get_selected():
  6354. obj_name = obj.options["name"]
  6355. try:
  6356. if isinstance(obj, FlatCAMExcellon):
  6357. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  6358. else:
  6359. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  6360. except Exception as e:
  6361. return "Operation failed: %s" % str(e)
  6362. def convert_any2gerber(self):
  6363. self.report_usage("convert_any2gerber()")
  6364. def initialize_geometry(obj_init, app):
  6365. apertures = {}
  6366. apid = 0
  6367. apertures[str(apid)] = {}
  6368. apertures[str(apid)]['geometry'] = []
  6369. for obj_orig in obj.solid_geometry:
  6370. new_elem = dict()
  6371. new_elem['solid'] = obj_orig
  6372. try:
  6373. new_elem['follow'] = obj_orig.exterior
  6374. except AttributeError:
  6375. pass
  6376. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  6377. apertures[str(apid)]['size'] = 0.0
  6378. apertures[str(apid)]['type'] = 'C'
  6379. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6380. obj_init.apertures = deepcopy(apertures)
  6381. def initialize_excellon(obj_init, app):
  6382. apertures = {}
  6383. apid = 10
  6384. for tool in obj.tools:
  6385. apertures[str(apid)] = {}
  6386. apertures[str(apid)]['geometry'] = []
  6387. for geo in obj.tools[tool]['solid_geometry']:
  6388. new_el = dict()
  6389. new_el['solid'] = geo
  6390. new_el['follow'] = geo.exterior
  6391. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  6392. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  6393. apertures[str(apid)]['type'] = 'C'
  6394. apid += 1
  6395. # create solid_geometry
  6396. solid_geometry = []
  6397. for apid in apertures:
  6398. for geo_el in apertures[apid]['geometry']:
  6399. solid_geometry.append(geo_el['solid'])
  6400. solid_geometry = MultiPolygon(solid_geometry)
  6401. solid_geometry = solid_geometry.buffer(0.0000001)
  6402. obj_init.solid_geometry = deepcopy(solid_geometry)
  6403. obj_init.apertures = deepcopy(apertures)
  6404. # clear the working objects (perhaps not necessary due of Python GC)
  6405. apertures.clear()
  6406. if not self.collection.get_selected():
  6407. log.warning("App.convert_any2gerber --> No object selected")
  6408. self.inform.emit('[WARNING_NOTCL] %s' %
  6409. _("No object is selected. Select an object and try again."))
  6410. return
  6411. for obj in self.collection.get_selected():
  6412. obj_name = obj.options["name"]
  6413. try:
  6414. if isinstance(obj, FlatCAMExcellon):
  6415. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  6416. elif isinstance(obj, FlatCAMGeometry):
  6417. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  6418. else:
  6419. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  6420. except Exception as e:
  6421. return "Operation failed: %s" % str(e)
  6422. def abort_all_tasks(self):
  6423. if self.abort_flag is False:
  6424. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  6425. self.abort_flag = True
  6426. def app_is_idle(self):
  6427. if self.abort_flag:
  6428. self.inform.emit('[WARNING_NOTCL] %s' %
  6429. _("The current task was gracefully closed on user request..."))
  6430. self.abort_flag = False
  6431. def on_selectall(self):
  6432. self.report_usage("on_selectall()")
  6433. # delete the possible selection box around a possible selected object
  6434. self.delete_selection_shape()
  6435. for name in self.collection.get_names():
  6436. self.collection.set_active(name)
  6437. curr_sel_obj = self.collection.get_by_name(name)
  6438. # create the selection box around the selected object
  6439. if self.defaults['global_selection_shape'] is True:
  6440. self.draw_selection_shape(curr_sel_obj)
  6441. def on_preferences(self):
  6442. """
  6443. Adds the Preferences in a Tab in Plot Area
  6444. :return:
  6445. """
  6446. # add the tab if it was closed
  6447. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  6448. # delete the absolute and relative position and messages in the infobar
  6449. self.ui.position_label.setText("")
  6450. self.ui.rel_position_label.setText("")
  6451. # Switch plot_area to preferences page
  6452. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  6453. # self.ui.show()
  6454. # detect changes in the preferences
  6455. for idx in range(self.ui.pref_tab_area.count()):
  6456. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6457. try:
  6458. try:
  6459. tb.textEdited.disconnect(self.on_preferences_edited)
  6460. except (TypeError, AttributeError):
  6461. pass
  6462. tb.textEdited.connect(self.on_preferences_edited)
  6463. except AttributeError:
  6464. pass
  6465. try:
  6466. try:
  6467. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6468. except (TypeError, AttributeError):
  6469. pass
  6470. tb.modificationChanged.connect(self.on_preferences_edited)
  6471. except AttributeError:
  6472. pass
  6473. try:
  6474. try:
  6475. tb.toggled.disconnect(self.on_preferences_edited)
  6476. except (TypeError, AttributeError):
  6477. pass
  6478. tb.toggled.connect(self.on_preferences_edited)
  6479. except AttributeError:
  6480. pass
  6481. try:
  6482. try:
  6483. tb.valueChanged.disconnect(self.on_preferences_edited)
  6484. except (TypeError, AttributeError):
  6485. pass
  6486. tb.valueChanged.connect(self.on_preferences_edited)
  6487. except AttributeError:
  6488. pass
  6489. try:
  6490. try:
  6491. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6492. except (TypeError, AttributeError):
  6493. pass
  6494. tb.currentIndexChanged.connect(self.on_preferences_edited)
  6495. except AttributeError:
  6496. pass
  6497. def on_preferences_edited(self):
  6498. self.inform.emit('[WARNING_NOTCL] %s' %
  6499. _("Preferences edited but not saved."))
  6500. for idx in range(self.ui.plot_tab_area.count()):
  6501. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  6502. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6503. self.preferences_changed_flag = True
  6504. def on_tools_database(self):
  6505. """
  6506. Adds the Tools Database in a Tab in Plot Area
  6507. :return:
  6508. """
  6509. for idx in range(self.ui.plot_tab_area.count()):
  6510. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6511. # there can be only one instance of Tools Database at one time
  6512. return
  6513. self.tools_db_tab = ToolsDB(
  6514. app=self,
  6515. parent=self.ui,
  6516. callback_on_edited=self.on_tools_db_edited,
  6517. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  6518. )
  6519. # add the tab if it was closed
  6520. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  6521. self.tools_db_tab.setObjectName("database_tab")
  6522. # delete the absolute and relative position and messages in the infobar
  6523. self.ui.position_label.setText("")
  6524. self.ui.rel_position_label.setText("")
  6525. # Switch plot_area to preferences page
  6526. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  6527. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  6528. self.tools_db_tab.ui_connect()
  6529. def on_tools_db_edited(self):
  6530. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  6531. for idx in range(self.ui.plot_tab_area.count()):
  6532. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6533. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6534. self.tools_db_changed_flag = True
  6535. def on_geometry_tool_add_from_db_executed(self, tool):
  6536. """
  6537. Here add the tool from DB in the selected geometry object
  6538. :return:
  6539. """
  6540. tool_from_db = deepcopy(tool)
  6541. obj = self.collection.get_active()
  6542. if isinstance(obj, FlatCAMGeometry):
  6543. obj.on_tool_from_db_inserted(tool=tool_from_db)
  6544. for idx in range(self.ui.plot_tab_area.count()):
  6545. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6546. wdg = self.ui.plot_tab_area.widget(idx)
  6547. wdg.deleteLater()
  6548. self.ui.plot_tab_area.removeTab(idx)
  6549. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  6550. else:
  6551. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  6552. def on_plot_area_tab_closed(self, title):
  6553. if title == _("Preferences"):
  6554. # disconnect
  6555. for idx in range(self.ui.pref_tab_area.count()):
  6556. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6557. try:
  6558. tb.textEdited.disconnect(self.on_preferences_edited)
  6559. except (TypeError, AttributeError):
  6560. pass
  6561. try:
  6562. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6563. except (TypeError, AttributeError):
  6564. pass
  6565. try:
  6566. tb.toggled.disconnect(self.on_preferences_edited)
  6567. except (TypeError, AttributeError):
  6568. pass
  6569. try:
  6570. tb.valueChanged.disconnect(self.on_preferences_edited)
  6571. except (TypeError, AttributeError):
  6572. pass
  6573. try:
  6574. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6575. except (TypeError, AttributeError):
  6576. pass
  6577. if self.preferences_changed_flag is True:
  6578. msgbox = QtWidgets.QMessageBox()
  6579. msgbox.setText(_("One or more values are changed.\n"
  6580. "Do you want to save the Preferences?"))
  6581. msgbox.setWindowTitle(_("Save Preferences"))
  6582. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6583. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6584. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6585. msgbox.setDefaultButton(bt_yes)
  6586. msgbox.exec_()
  6587. response = msgbox.clickedButton()
  6588. if response == bt_yes:
  6589. self.on_save_button(save_to_file=True)
  6590. self.inform.emit('[success] %s' % _("Preferences saved."))
  6591. else:
  6592. self.preferences_changed_flag = False
  6593. self.inform.emit('')
  6594. return
  6595. if title == _("Tools Database"):
  6596. # disconnect the signals from the table widget in tab
  6597. self.tools_db_tab.ui_disconnect()
  6598. if self.tools_db_changed_flag is True:
  6599. msgbox = QtWidgets.QMessageBox()
  6600. msgbox.setText(_("One or more Tools are edited.\n"
  6601. "Do you want to update the Tools Database?"))
  6602. msgbox.setWindowTitle(_("Save Tools Database"))
  6603. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6604. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6605. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6606. msgbox.setDefaultButton(bt_yes)
  6607. msgbox.exec_()
  6608. response = msgbox.clickedButton()
  6609. if response == bt_yes:
  6610. self.tools_db_tab.on_save_tools_db()
  6611. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  6612. else:
  6613. self.tools_db_changed_flag = False
  6614. self.inform.emit('')
  6615. return
  6616. self.tools_db_tab.deleteLater()
  6617. if title == _("Code Editor"):
  6618. self.toggle_codeeditor = False
  6619. if title == _("Bookmarks Manager"):
  6620. self.book_dialog_tab.rebuild_actions()
  6621. self.book_dialog_tab.deleteLater()
  6622. def on_flipy(self):
  6623. self.report_usage("on_flipy()")
  6624. obj_list = self.collection.get_selected()
  6625. xminlist = []
  6626. yminlist = []
  6627. xmaxlist = []
  6628. ymaxlist = []
  6629. if not obj_list:
  6630. self.inform.emit('[WARNING_NOTCL] %s' %
  6631. _("No object selected to Flip on Y axis."))
  6632. else:
  6633. try:
  6634. # first get a bounding box to fit all
  6635. for obj in obj_list:
  6636. xmin, ymin, xmax, ymax = obj.bounds()
  6637. xminlist.append(xmin)
  6638. yminlist.append(ymin)
  6639. xmaxlist.append(xmax)
  6640. ymaxlist.append(ymax)
  6641. # get the minimum x,y and maximum x,y for all objects selected
  6642. xminimal = min(xminlist)
  6643. yminimal = min(yminlist)
  6644. xmaximal = max(xmaxlist)
  6645. ymaximal = max(ymaxlist)
  6646. px = 0.5 * (xminimal + xmaximal)
  6647. py = 0.5 * (yminimal + ymaximal)
  6648. # execute mirroring
  6649. for obj in obj_list:
  6650. obj.mirror('X', [px, py])
  6651. obj.plot()
  6652. self.object_changed.emit(obj)
  6653. self.inform.emit('[success] %s' %
  6654. _("Flip on Y axis done."))
  6655. except Exception as e:
  6656. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6657. return
  6658. def on_flipx(self):
  6659. self.report_usage("on_flipx()")
  6660. obj_list = self.collection.get_selected()
  6661. xminlist = []
  6662. yminlist = []
  6663. xmaxlist = []
  6664. ymaxlist = []
  6665. if not obj_list:
  6666. self.inform.emit('[WARNING_NOTCL] %s' %
  6667. _("No object selected to Flip on X axis."))
  6668. else:
  6669. try:
  6670. # first get a bounding box to fit all
  6671. for obj in obj_list:
  6672. xmin, ymin, xmax, ymax = obj.bounds()
  6673. xminlist.append(xmin)
  6674. yminlist.append(ymin)
  6675. xmaxlist.append(xmax)
  6676. ymaxlist.append(ymax)
  6677. # get the minimum x,y and maximum x,y for all objects selected
  6678. xminimal = min(xminlist)
  6679. yminimal = min(yminlist)
  6680. xmaximal = max(xmaxlist)
  6681. ymaximal = max(ymaxlist)
  6682. px = 0.5 * (xminimal + xmaximal)
  6683. py = 0.5 * (yminimal + ymaximal)
  6684. # execute mirroring
  6685. for obj in obj_list:
  6686. obj.mirror('Y', [px, py])
  6687. obj.plot()
  6688. self.object_changed.emit(obj)
  6689. self.inform.emit('[success] %s' %
  6690. _("Flip on X axis done."))
  6691. except Exception as e:
  6692. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6693. return
  6694. def on_rotate(self, silent=False, preset=None):
  6695. self.report_usage("on_rotate()")
  6696. obj_list = self.collection.get_selected()
  6697. xminlist = []
  6698. yminlist = []
  6699. xmaxlist = []
  6700. ymaxlist = []
  6701. if not obj_list:
  6702. self.inform.emit('[WARNING_NOTCL] %s' %
  6703. _("No object selected to Rotate."))
  6704. else:
  6705. if silent is False:
  6706. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6707. min=-360, max=360, decimals=4,
  6708. init_val=float(self.defaults['tools_transform_rotate']))
  6709. num, ok = rotatebox.get_value()
  6710. else:
  6711. num = preset
  6712. ok = True
  6713. if ok:
  6714. try:
  6715. # first get a bounding box to fit all
  6716. for obj in obj_list:
  6717. xmin, ymin, xmax, ymax = obj.bounds()
  6718. xminlist.append(xmin)
  6719. yminlist.append(ymin)
  6720. xmaxlist.append(xmax)
  6721. ymaxlist.append(ymax)
  6722. # get the minimum x,y and maximum x,y for all objects selected
  6723. xminimal = min(xminlist)
  6724. yminimal = min(yminlist)
  6725. xmaximal = max(xmaxlist)
  6726. ymaximal = max(ymaxlist)
  6727. px = 0.5 * (xminimal + xmaximal)
  6728. py = 0.5 * (yminimal + ymaximal)
  6729. for sel_obj in obj_list:
  6730. sel_obj.rotate(-float(num), point=(px, py))
  6731. sel_obj.plot()
  6732. self.object_changed.emit(sel_obj)
  6733. self.inform.emit('[success] %s' %
  6734. _("Rotation done."))
  6735. except Exception as e:
  6736. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  6737. return
  6738. def on_skewx(self):
  6739. self.report_usage("on_skewx()")
  6740. obj_list = self.collection.get_selected()
  6741. xminlist = []
  6742. yminlist = []
  6743. if not obj_list:
  6744. self.inform.emit('[WARNING_NOTCL] %s' %
  6745. _("No object selected to Skew/Shear on X axis."))
  6746. else:
  6747. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6748. min=-360, max=360, decimals=4,
  6749. init_val=float(self.defaults['tools_transform_skew_x']))
  6750. num, ok = skewxbox.get_value()
  6751. if ok:
  6752. # first get a bounding box to fit all
  6753. for obj in obj_list:
  6754. xmin, ymin, xmax, ymax = obj.bounds()
  6755. xminlist.append(xmin)
  6756. yminlist.append(ymin)
  6757. # get the minimum x,y and maximum x,y for all objects selected
  6758. xminimal = min(xminlist)
  6759. yminimal = min(yminlist)
  6760. for obj in obj_list:
  6761. obj.skew(num, 0, point=(xminimal, yminimal))
  6762. obj.plot()
  6763. self.object_changed.emit(obj)
  6764. self.inform.emit('[success] %s' %
  6765. _("Skew on X axis done."))
  6766. def on_skewy(self):
  6767. self.report_usage("on_skewy()")
  6768. obj_list = self.collection.get_selected()
  6769. xminlist = []
  6770. yminlist = []
  6771. if not obj_list:
  6772. self.inform.emit('[WARNING_NOTCL] %s' %
  6773. _("No object selected to Skew/Shear on Y axis."))
  6774. else:
  6775. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6776. min=-360, max=360, decimals=4,
  6777. init_val=float(self.defaults['tools_transform_skew_y']))
  6778. num, ok = skewybox.get_value()
  6779. if ok:
  6780. # first get a bounding box to fit all
  6781. for obj in obj_list:
  6782. xmin, ymin, xmax, ymax = obj.bounds()
  6783. xminlist.append(xmin)
  6784. yminlist.append(ymin)
  6785. # get the minimum x,y and maximum x,y for all objects selected
  6786. xminimal = min(xminlist)
  6787. yminimal = min(yminlist)
  6788. for obj in obj_list:
  6789. obj.skew(0, num, point=(xminimal, yminimal))
  6790. obj.plot()
  6791. self.object_changed.emit(obj)
  6792. self.inform.emit('[success] %s' %
  6793. _("Skew on Y axis done."))
  6794. def on_plots_updated(self):
  6795. """
  6796. Callback used to report when the plots have changed.
  6797. Adjust axes and zooms to fit.
  6798. :return: None
  6799. """
  6800. if self.is_legacy is False:
  6801. self.plotcanvas.update() # TODO: Need update canvas?
  6802. else:
  6803. self.plotcanvas.auto_adjust_axes()
  6804. self.on_zoom_fit(None)
  6805. self.collection.update_view()
  6806. # self.inform.emit(_("Plots updated ..."))
  6807. # TODO: Rework toolbar 'clear', 'replot' functions
  6808. def on_toolbar_replot(self):
  6809. """
  6810. Callback for toolbar button. Re-plots all objects.
  6811. :return: None
  6812. """
  6813. self.report_usage("on_toolbar_replot")
  6814. self.log.debug("on_toolbar_replot()")
  6815. try:
  6816. self.collection.get_active().read_form()
  6817. except AttributeError:
  6818. self.log.debug("on_toolbar_replot(): AttributeError")
  6819. pass
  6820. self.plot_all()
  6821. def on_row_activated(self, index):
  6822. if index.isValid():
  6823. if index.internalPointer().parent_item != self.collection.root_item:
  6824. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6825. self.collection.on_item_activated(index)
  6826. def on_row_selected(self, obj_name):
  6827. # this is a special string; when received it will make all entries unchecked
  6828. # it mean we clicked outside of the items and deselected all
  6829. if obj_name == 'none':
  6830. for act in self.ui.menuobjects.actions():
  6831. act.setChecked(False)
  6832. return
  6833. # get the name of the selected objects and add them to a list
  6834. name_list = list()
  6835. for obj in self.collection.get_selected():
  6836. name_list.append(obj.options['name'])
  6837. # set all actions as unchecked but the ones selected make them checked
  6838. for act in self.ui.menuobjects.actions():
  6839. act.setChecked(False)
  6840. if act.text() in name_list:
  6841. act.setChecked(True)
  6842. def on_collection_updated(self, obj, state, old_name):
  6843. """
  6844. Create a menu from the object loaded in the collection.
  6845. TODO: should use the collection model to do this
  6846. :param obj: object that was changd (added, deleted, renamed)
  6847. :param state: what was done with the objectCand be: added, deleted, delete_all, renamed
  6848. :param old_name: the old name of the object before the action that triggered this slot happened
  6849. :return: None
  6850. """
  6851. icon_files = {
  6852. "gerber": self.resource_location + "/flatcam_icon16.png",
  6853. "excellon": self.resource_location + "/drill16.png",
  6854. "cncjob": self.resource_location + "/cnc16.png",
  6855. "geometry": self.resource_location + "/geometry16.png",
  6856. "script": self.resource_location + "/script_new16.png",
  6857. "document": self.resource_location + "/notes16_1.png"
  6858. }
  6859. if state == 'append':
  6860. for act in self.ui.menuobjects.actions():
  6861. try:
  6862. act.triggered.disconnect()
  6863. except TypeError:
  6864. pass
  6865. self.ui.menuobjects.clear()
  6866. gerber_list = list()
  6867. exc_list = list()
  6868. cncjob_list = list()
  6869. geo_list = list()
  6870. script_list = list()
  6871. doc_list = list()
  6872. for name in self.collection.get_names():
  6873. obj_named = self.collection.get_by_name(name)
  6874. if obj_named.kind == 'gerber':
  6875. gerber_list.append(name)
  6876. elif obj_named.kind == 'excellon':
  6877. exc_list.append(name)
  6878. elif obj_named.kind == 'cncjob':
  6879. cncjob_list.append(name)
  6880. elif obj_named.kind == 'geometry':
  6881. geo_list.append(name)
  6882. elif obj_named.kind == 'script':
  6883. script_list.append(name)
  6884. elif obj_named.kind == 'document':
  6885. doc_list.append(name)
  6886. def add_act(o_name):
  6887. obj_for_icon = self.collection.get_by_name(o_name)
  6888. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6889. add_action.setCheckable(True)
  6890. add_action.setText(o_name)
  6891. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  6892. add_action.triggered.connect(
  6893. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  6894. self.collection.set_inactive(o_name))
  6895. self.ui.menuobjects.addAction(add_action)
  6896. for name in gerber_list:
  6897. add_act(name)
  6898. self.ui.menuobjects.addSeparator()
  6899. for name in exc_list:
  6900. add_act(name)
  6901. self.ui.menuobjects.addSeparator()
  6902. for name in cncjob_list:
  6903. add_act(name)
  6904. self.ui.menuobjects.addSeparator()
  6905. for name in geo_list:
  6906. add_act(name)
  6907. self.ui.menuobjects.addSeparator()
  6908. for name in script_list:
  6909. add_act(name)
  6910. self.ui.menuobjects.addSeparator()
  6911. for name in doc_list:
  6912. add_act(name)
  6913. self.ui.menuobjects.addSeparator()
  6914. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6915. QtGui.QIcon(self.resource_location + '/select_all.png'),
  6916. _('Select All')
  6917. )
  6918. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6919. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  6920. _('Deselect All')
  6921. )
  6922. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6923. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6924. elif state == 'delete':
  6925. for act in self.ui.menuobjects.actions():
  6926. if act.text() == obj.options['name']:
  6927. try:
  6928. act.triggered.disconnect()
  6929. except TypeError:
  6930. pass
  6931. self.ui.menuobjects.removeAction(act)
  6932. break
  6933. elif state == 'rename':
  6934. for act in self.ui.menuobjects.actions():
  6935. if act.text() == old_name:
  6936. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6937. add_action.setText(obj.options['name'])
  6938. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  6939. add_action.triggered.connect(
  6940. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  6941. self.collection.set_inactive(obj.options['name']))
  6942. self.ui.menuobjects.insertAction(act, add_action)
  6943. try:
  6944. act.triggered.disconnect()
  6945. except TypeError:
  6946. pass
  6947. self.ui.menuobjects.removeAction(act)
  6948. break
  6949. elif state == 'delete_all':
  6950. for act in self.ui.menuobjects.actions():
  6951. try:
  6952. act.triggered.disconnect()
  6953. except TypeError:
  6954. pass
  6955. self.ui.menuobjects.clear()
  6956. self.ui.menuobjects.addSeparator()
  6957. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  6958. QtGui.QIcon(self.resource_location + '/select_all.png'),
  6959. _('Select All')
  6960. )
  6961. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  6962. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  6963. _('Deselect All')
  6964. )
  6965. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  6966. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  6967. def on_objects_selection(self, on_off):
  6968. obj_list = self.collection.get_names()
  6969. if on_off is True:
  6970. self.collection.set_all_active()
  6971. for act in self.ui.menuobjects.actions():
  6972. try:
  6973. act.setChecked(True)
  6974. except Exception:
  6975. pass
  6976. if obj_list:
  6977. self.inform.emit('[selected] %s' % _("All objects are selected."))
  6978. else:
  6979. self.collection.set_all_inactive()
  6980. for act in self.ui.menuobjects.actions():
  6981. try:
  6982. act.setChecked(False)
  6983. except Exception:
  6984. pass
  6985. if obj_list:
  6986. self.inform.emit('%s' % _("Objects selection is cleared."))
  6987. else:
  6988. self.inform.emit('')
  6989. def grid_status(self):
  6990. if self.ui.grid_snap_btn.isChecked():
  6991. return True
  6992. else:
  6993. return False
  6994. def populate_cmenu_grids(self):
  6995. units = self.defaults['units'].lower()
  6996. self.ui.cmenu_gridmenu.clear()
  6997. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6998. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  6999. _("Grid On/Off"))
  7000. grid_toggle.setCheckable(True)
  7001. if self.grid_status() == True:
  7002. grid_toggle.setChecked(True)
  7003. else:
  7004. grid_toggle.setChecked(False)
  7005. self.ui.cmenu_gridmenu.addSeparator()
  7006. for grid in sorted_list:
  7007. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  7008. "%s" % str(grid))
  7009. action.triggered.connect(self.set_grid)
  7010. self.ui.cmenu_gridmenu.addSeparator()
  7011. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  7012. _("Add"))
  7013. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  7014. _("Delete"))
  7015. grid_add.triggered.connect(self.on_grid_add)
  7016. grid_delete.triggered.connect(self.on_grid_delete)
  7017. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  7018. def set_grid(self):
  7019. self.ui.grid_gap_x_entry.setText(self.sender().text())
  7020. self.ui.grid_gap_y_entry.setText(self.sender().text())
  7021. def on_grid_add(self):
  7022. # ## Current application units in lower Case
  7023. units = self.defaults['units'].lower()
  7024. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  7025. text=_('Enter a Grid Value:'),
  7026. min=0.0000, max=99.9999, decimals=4)
  7027. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  7028. val, ok = grid_add_popup.get_value()
  7029. if ok:
  7030. if float(val) == 0:
  7031. self.inform.emit('[WARNING_NOTCL] %s' %
  7032. _("Please enter a grid value with non-zero value, in Float format."))
  7033. return
  7034. else:
  7035. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  7036. self.defaults["global_grid_context_menu"][str(units)].append(val)
  7037. self.inform.emit('[success] %s...' %
  7038. _("New Grid added"))
  7039. else:
  7040. self.inform.emit('[WARNING_NOTCL] %s...' %
  7041. _("Grid already exists"))
  7042. else:
  7043. self.inform.emit('[WARNING_NOTCL] %s...' %
  7044. _("Adding New Grid cancelled"))
  7045. def on_grid_delete(self):
  7046. # ## Current application units in lower Case
  7047. units = self.defaults['units'].lower()
  7048. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  7049. text='Enter a Grid Value:',
  7050. min=0.0000, max=99.9999, decimals=4)
  7051. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  7052. val, ok = grid_del_popup.get_value()
  7053. if ok:
  7054. if float(val) == 0:
  7055. self.inform.emit('[WARNING_NOTCL] %s' %
  7056. _("Please enter a grid value with non-zero value, in Float format."))
  7057. return
  7058. else:
  7059. try:
  7060. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  7061. except ValueError:
  7062. self.inform.emit('[ERROR_NOTCL]%s...' %
  7063. _(" Grid Value does not exist"))
  7064. return
  7065. self.inform.emit('[success] %s...' %
  7066. _("Grid Value deleted"))
  7067. else:
  7068. self.inform.emit('[WARNING_NOTCL] %s...' %
  7069. _("Delete Grid value cancelled"))
  7070. def on_shortcut_list(self):
  7071. self.report_usage("on_shortcut_list()")
  7072. # add the tab if it was closed
  7073. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  7074. # delete the absolute and relative position and messages in the infobar
  7075. self.ui.position_label.setText("")
  7076. self.ui.rel_position_label.setText("")
  7077. # Switch plot_area to preferences page
  7078. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  7079. # self.ui.show()
  7080. def on_select_tab(self, name):
  7081. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  7082. if self.ui.splitter.sizes()[0] == 0:
  7083. self.ui.splitter.setSizes([1, 1])
  7084. else:
  7085. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  7086. self.ui.splitter.setSizes([0, 1])
  7087. if name == 'project':
  7088. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7089. elif name == 'selected':
  7090. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7091. elif name == 'tool':
  7092. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  7093. def on_copy_name(self):
  7094. self.report_usage("on_copy_name()")
  7095. obj = self.collection.get_active()
  7096. try:
  7097. name = obj.options["name"]
  7098. except AttributeError:
  7099. log.debug("on_copy_name() --> No object selected to copy it's name")
  7100. self.inform.emit('[WARNING_NOTCL]%s' %
  7101. _(" No object selected to copy it's name"))
  7102. return
  7103. self.clipboard.setText(name)
  7104. self.inform.emit(_("Name copied on clipboard ..."))
  7105. def on_mouse_click_over_plot(self, event):
  7106. """
  7107. Default actions are:
  7108. :param event: Contains information about the event, like which button
  7109. was clicked, the pixel coordinates and the axes coordinates.
  7110. :return: None
  7111. """
  7112. self.pos = list()
  7113. if self.is_legacy is False:
  7114. event_pos = event.pos
  7115. pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  7116. # Set the mouse button for panning
  7117. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7118. else:
  7119. event_pos = (event.xdata, event.ydata)
  7120. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7121. pan_button = 3 if self.defaults["global_pan_button"] == '2'else 2
  7122. # So it can receive key presses
  7123. self.plotcanvas.native.setFocus()
  7124. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7125. if self.grid_status() == True:
  7126. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  7127. else:
  7128. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  7129. try:
  7130. if event.button == 1:
  7131. # Reset here the relative coordinates so there is a new reference on the click position
  7132. if self.rel_point1 is None:
  7133. self.rel_point1 = self.pos
  7134. else:
  7135. self.rel_point2 = copy(self.rel_point1)
  7136. self.rel_point1 = self.pos
  7137. self.on_mouse_move_over_plot(event, origin_click=True)
  7138. except Exception as e:
  7139. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  7140. def on_mouse_double_click_over_plot(self, event):
  7141. if event.button == 1:
  7142. self.doubleclick = True
  7143. def on_mouse_move_over_plot(self, event, origin_click=None):
  7144. """
  7145. Callback for the mouse motion event over the plot.
  7146. :param event: Contains information about the event.
  7147. :param origin_click
  7148. :return: None
  7149. """
  7150. if self.is_legacy is False:
  7151. event_pos = event.pos
  7152. if self.defaults["global_pan_button"] == '2':
  7153. pan_button = 2
  7154. else:
  7155. pan_button = 3
  7156. self.event_is_dragging = event.is_dragging
  7157. else:
  7158. event_pos = (event.xdata, event.ydata)
  7159. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7160. if self.defaults["global_pan_button"] == '2':
  7161. pan_button = 3
  7162. else:
  7163. pan_button = 2
  7164. self.event_is_dragging = self.plotcanvas.is_dragging
  7165. # So it can receive key presses
  7166. self.plotcanvas.native.setFocus()
  7167. self.pos_jump = event_pos
  7168. self.ui.popMenu.mouse_is_panning = False
  7169. if not origin_click:
  7170. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  7171. if event.button == pan_button and self.event_is_dragging == 1:
  7172. self.ui.popMenu.mouse_is_panning = True
  7173. return
  7174. if self.rel_point1 is not None:
  7175. try: # May fail in case mouse not within axes
  7176. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7177. if self.grid_status() == True:
  7178. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7179. # Update cursor
  7180. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  7181. symbol='++', edge_color=self.cursor_color_3D,
  7182. size=self.defaults["global_cursor_size"])
  7183. else:
  7184. pos = (pos_canvas[0], pos_canvas[1])
  7185. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  7186. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  7187. dx = pos[0] - float(self.rel_point1[0])
  7188. dy = pos[1] - float(self.rel_point1[1])
  7189. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  7190. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  7191. self.mouse = [pos[0], pos[1]]
  7192. # if the mouse is moved and the LMB is clicked then the action is a selection
  7193. if self.event_is_dragging == 1 and event.button == 1:
  7194. self.delete_selection_shape()
  7195. if dx < 0:
  7196. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  7197. face_color=self.defaults['global_alt_sel_fill'])
  7198. self.selection_type = False
  7199. elif dx > 0:
  7200. self.draw_moving_selection_shape(self.pos, pos)
  7201. self.selection_type = True
  7202. else:
  7203. self.selection_type = None
  7204. # hover effect - enabled in Preferences -> General -> GUI Settings
  7205. if self.defaults['global_hover']:
  7206. for obj in self.collection.get_list():
  7207. try:
  7208. # select the object(s) only if it is enabled (plotted)
  7209. if obj.options['plot']:
  7210. if obj not in self.collection.get_selected():
  7211. poly_obj = Polygon(
  7212. [(obj.options['xmin'], obj.options['ymin']),
  7213. (obj.options['xmax'], obj.options['ymin']),
  7214. (obj.options['xmax'], obj.options['ymax']),
  7215. (obj.options['xmin'], obj.options['ymax'])]
  7216. )
  7217. if Point(pos).within(poly_obj):
  7218. if obj.isHovering is False:
  7219. obj.isHovering = True
  7220. obj.notHovering = True
  7221. # create the selection box around the selected object
  7222. self.draw_hover_shape(obj, color='#d1e0e0FF')
  7223. else:
  7224. if obj.notHovering is True:
  7225. obj.notHovering = False
  7226. obj.isHovering = False
  7227. self.delete_hover_shape()
  7228. except Exception:
  7229. # the Exception here will happen if we try to select on screen and we have an
  7230. # newly (and empty) just created Geometry or Excellon object that do not have the
  7231. # xmin, xmax, ymin, ymax options.
  7232. # In this case poly_obj creation (see above) will fail
  7233. pass
  7234. except Exception:
  7235. self.ui.position_label.setText("")
  7236. self.ui.rel_position_label.setText("")
  7237. self.mouse = None
  7238. def on_mouse_click_release_over_plot(self, event):
  7239. """
  7240. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  7241. and has been registered in ''self.__init__()''.
  7242. :param event: contains information about the event.
  7243. :return:
  7244. """
  7245. if self.is_legacy is False:
  7246. event_pos = event.pos
  7247. right_button = 2
  7248. else:
  7249. event_pos = (event.xdata, event.ydata)
  7250. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7251. right_button = 3
  7252. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7253. if self.grid_status() == True:
  7254. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7255. else:
  7256. pos = (pos_canvas[0], pos_canvas[1])
  7257. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  7258. # canvas menu
  7259. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  7260. self.cursor = QtGui.QCursor()
  7261. self.populate_cmenu_grids()
  7262. self.ui.popMenu.popup(self.cursor.pos())
  7263. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  7264. # selection and then select a type of selection ("enclosing" or "touching")
  7265. if event.button == 1: # left click
  7266. modifiers = QtWidgets.QApplication.keyboardModifiers()
  7267. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  7268. if modifiers == QtCore.Qt.ShiftModifier:
  7269. # do not auto open the Project Tab
  7270. self.click_noproject = True
  7271. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  7272. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  7273. return
  7274. if self.doubleclick is True:
  7275. self.doubleclick = False
  7276. if self.collection.get_selected():
  7277. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7278. if self.ui.splitter.sizes()[0] == 0:
  7279. self.ui.splitter.setSizes([1, 1])
  7280. try:
  7281. # delete the selection shape(S) as it may be in the way
  7282. self.delete_selection_shape()
  7283. self.delete_hover_shape()
  7284. except Exception as e:
  7285. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  7286. return
  7287. else:
  7288. if self.selection_type is not None:
  7289. try:
  7290. self.selection_area_handler(self.pos, pos, self.selection_type)
  7291. self.selection_type = None
  7292. except Exception as e:
  7293. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  7294. return
  7295. else:
  7296. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  7297. if key_modifier == QtCore.Qt.ShiftModifier:
  7298. mod_key = 'Shift'
  7299. elif key_modifier == QtCore.Qt.ControlModifier:
  7300. mod_key = 'Control'
  7301. else:
  7302. mod_key = None
  7303. try:
  7304. if mod_key == self.defaults["global_mselect_key"]:
  7305. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  7306. # deselect, and if it's not selected then it will be selected
  7307. # If there is no active command (self.command_active is None) then we check if we clicked
  7308. # on a object by checking the bounding limits against mouse click position
  7309. if self.command_active is None:
  7310. self.select_objects(key='CTRL')
  7311. self.delete_hover_shape()
  7312. else:
  7313. # If there is no active command (self.command_active is None) then we check if we clicked
  7314. # on a object by checking the bounding limits against mouse click position
  7315. if self.command_active is None:
  7316. self.select_objects()
  7317. self.delete_hover_shape()
  7318. except Exception as e:
  7319. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  7320. return
  7321. def selection_area_handler(self, start_pos, end_pos, sel_type):
  7322. """
  7323. :param start_pos: mouse position when the selection LMB click was done
  7324. :param end_pos: mouse position when the left mouse button is released
  7325. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  7326. :return:
  7327. """
  7328. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  7329. # delete previous selection shape
  7330. self.delete_selection_shape()
  7331. # make all objects inactive
  7332. self.collection.set_all_inactive()
  7333. for obj in self.collection.get_list():
  7334. try:
  7335. # select the object(s) only if it is enabled (plotted)
  7336. if obj.options['plot']:
  7337. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  7338. (obj.options['xmax'], obj.options['ymin']),
  7339. (obj.options['xmax'], obj.options['ymax']),
  7340. (obj.options['xmin'], obj.options['ymax'])])
  7341. if sel_type is True:
  7342. if poly_obj.within(poly_selection):
  7343. # create the selection box around the selected object
  7344. if self.defaults['global_selection_shape'] is True:
  7345. self.draw_selection_shape(obj)
  7346. self.collection.set_active(obj.options['name'])
  7347. else:
  7348. if poly_selection.intersects(poly_obj):
  7349. # create the selection box around the selected object
  7350. if self.defaults['global_selection_shape'] is True:
  7351. self.draw_selection_shape(obj)
  7352. self.collection.set_active(obj.options['name'])
  7353. except Exception as e:
  7354. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  7355. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  7356. # In this case poly_obj creation (see above) will fail
  7357. log.debug("App.selection_area_handler() --> %s" % str(e))
  7358. def select_objects(self, key=None):
  7359. """
  7360. Will select objects clicked on canvas
  7361. :param key: for future use in cumulative selection
  7362. :return:
  7363. """
  7364. # list where we store the overlapped objects under our mouse left click position
  7365. objects_under_the_click_list = []
  7366. # Populate the list with the overlapped objects on the click position
  7367. curr_x, curr_y = self.pos
  7368. for obj in self.all_objects_list:
  7369. # FlatCAMScript and FlatCAMDocument objects can't be selected
  7370. if isinstance(obj, FlatCAMScript) or isinstance(obj, FlatCAMDocument):
  7371. continue
  7372. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  7373. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  7374. if obj.options['name'] not in objects_under_the_click_list:
  7375. if obj.options['plot']:
  7376. # add objects to the objects_under_the_click list only if the object is plotted
  7377. # (active and not disabled)
  7378. objects_under_the_click_list.append(obj.options['name'])
  7379. try:
  7380. if objects_under_the_click_list:
  7381. curr_sel_obj = self.collection.get_active()
  7382. # case when there is only an object under the click and we toggle it
  7383. if len(objects_under_the_click_list) == 1:
  7384. if curr_sel_obj is None:
  7385. self.collection.set_active(objects_under_the_click_list[0])
  7386. curr_sel_obj = self.collection.get_active()
  7387. # create the selection box around the selected object
  7388. if self.defaults['global_selection_shape'] is True:
  7389. self.draw_selection_shape(curr_sel_obj)
  7390. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  7391. self.on_objects_selection(False)
  7392. self.delete_selection_shape()
  7393. self.collection.set_active(objects_under_the_click_list[0])
  7394. curr_sel_obj = self.collection.get_active()
  7395. # create the selection box around the selected object
  7396. if self.defaults['global_selection_shape'] is True:
  7397. self.draw_selection_shape(curr_sel_obj)
  7398. self.selected_message(curr_sel_obj=curr_sel_obj)
  7399. else:
  7400. self.on_objects_selection(False)
  7401. self.delete_selection_shape()
  7402. if self.call_source != 'app':
  7403. self.call_source = 'app'
  7404. self.selected_message(curr_sel_obj=curr_sel_obj)
  7405. else:
  7406. # If there is no selected object
  7407. # make active the first element of the overlapped objects list
  7408. if self.collection.get_active() is None:
  7409. self.collection.set_active(objects_under_the_click_list[0])
  7410. name_sel_obj = self.collection.get_active().options['name']
  7411. # In case that there is a selected object but it is not in the overlapped object list
  7412. # make that object inactive and activate the first element in the overlapped object list
  7413. if name_sel_obj not in objects_under_the_click_list:
  7414. self.collection.set_inactive(name_sel_obj)
  7415. name_sel_obj = objects_under_the_click_list[0]
  7416. self.collection.set_active(name_sel_obj)
  7417. else:
  7418. sel_idx = objects_under_the_click_list.index(name_sel_obj)
  7419. self.collection.set_all_inactive()
  7420. self.collection.set_active(objects_under_the_click_list[(sel_idx + 1) %
  7421. len(objects_under_the_click_list)])
  7422. curr_sel_obj = self.collection.get_active()
  7423. # delete the possible selection box around a possible selected object
  7424. self.delete_selection_shape()
  7425. # create the selection box around the selected object
  7426. if self.defaults['global_selection_shape'] is True:
  7427. self.draw_selection_shape(curr_sel_obj)
  7428. self.selected_message(curr_sel_obj=curr_sel_obj)
  7429. else:
  7430. # deselect everything
  7431. self.on_objects_selection(False)
  7432. # delete the possible selection box around a possible selected object
  7433. self.delete_selection_shape()
  7434. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  7435. # only when working on App
  7436. if self.call_source == 'app':
  7437. if self.click_noproject is False:
  7438. # if the Tool Tab is in focus don't change focus to Project Tab
  7439. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  7440. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7441. else:
  7442. # restore auto open the Project Tab
  7443. self.click_noproject = False
  7444. # delete any text in the status bar, implicitly the last object name that was selected
  7445. # self.inform.emit("")
  7446. else:
  7447. self.call_source = 'app'
  7448. except Exception as e:
  7449. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  7450. def selected_message(self, curr_sel_obj):
  7451. if curr_sel_obj:
  7452. if curr_sel_obj.kind == 'gerber':
  7453. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  7454. color='green',
  7455. name=str(curr_sel_obj.options['name']),
  7456. tx=_("selected"))
  7457. )
  7458. elif curr_sel_obj.kind == 'excellon':
  7459. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  7460. color='brown',
  7461. name=str(curr_sel_obj.options['name']),
  7462. tx=_("selected"))
  7463. )
  7464. elif curr_sel_obj.kind == 'cncjob':
  7465. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  7466. color='blue',
  7467. name=str(curr_sel_obj.options['name']),
  7468. tx=_("selected"))
  7469. )
  7470. elif curr_sel_obj.kind == 'geometry':
  7471. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  7472. color='red',
  7473. name=str(curr_sel_obj.options['name']),
  7474. tx=_("selected"))
  7475. )
  7476. def delete_hover_shape(self):
  7477. self.hover_shapes.clear()
  7478. self.hover_shapes.redraw()
  7479. def draw_hover_shape(self, sel_obj, color=None):
  7480. """
  7481. :param sel_obj: the object for which the hover shape must be drawn
  7482. :return:
  7483. """
  7484. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7485. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7486. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7487. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7488. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  7489. if self.defaults['units'].upper() == 'MM':
  7490. hover_rect = hover_rect.buffer(-0.1)
  7491. hover_rect = hover_rect.buffer(0.2)
  7492. else:
  7493. hover_rect = hover_rect.buffer(-0.00393)
  7494. hover_rect = hover_rect.buffer(0.00787)
  7495. # if color:
  7496. # face = Color(color)
  7497. # face.alpha = 0.2
  7498. # outline = Color(color, alpha=0.8)
  7499. # else:
  7500. # face = Color(self.defaults['global_sel_fill'])
  7501. # face.alpha = 0.2
  7502. # outline = self.defaults['global_sel_line']
  7503. if color:
  7504. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7505. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7506. else:
  7507. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7508. outline = self.defaults['global_sel_line']
  7509. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  7510. if self.is_legacy is True:
  7511. self.hover_shapes.redraw()
  7512. def delete_selection_shape(self):
  7513. self.move_tool.sel_shapes.clear()
  7514. self.move_tool.sel_shapes.redraw()
  7515. def draw_selection_shape(self, sel_obj, color=None):
  7516. """
  7517. :param sel_obj: the object for which the selection shape must be drawn
  7518. :return:
  7519. """
  7520. if sel_obj is None:
  7521. return
  7522. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7523. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7524. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7525. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7526. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7527. if self.defaults['units'].upper() == 'MM':
  7528. sel_rect = sel_rect.buffer(-0.1)
  7529. sel_rect = sel_rect.buffer(0.2)
  7530. else:
  7531. sel_rect = sel_rect.buffer(-0.00393)
  7532. sel_rect = sel_rect.buffer(0.00787)
  7533. if color:
  7534. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7535. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7536. else:
  7537. if self.is_legacy is False:
  7538. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7539. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  7540. else:
  7541. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  7542. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  7543. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  7544. color=outline,
  7545. face_color=face,
  7546. update=True,
  7547. layer=0,
  7548. tolerance=None))
  7549. if self.is_legacy is True:
  7550. self.move_tool.sel_shapes.redraw()
  7551. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  7552. """
  7553. :param old_coords: old coordinates
  7554. :param coords: new coordinates
  7555. :return:
  7556. """
  7557. if 'color' in kwargs:
  7558. color = kwargs['color']
  7559. else:
  7560. color = self.defaults['global_sel_line']
  7561. if 'face_color' in kwargs:
  7562. face_color = kwargs['face_color']
  7563. else:
  7564. face_color = self.defaults['global_sel_fill']
  7565. if 'face_alpha' in kwargs:
  7566. face_alpha = kwargs['face_alpha']
  7567. else:
  7568. face_alpha = 0.3
  7569. x0, y0 = old_coords
  7570. x1, y1 = coords
  7571. pt1 = (x0, y0)
  7572. pt2 = (x1, y0)
  7573. pt3 = (x1, y1)
  7574. pt4 = (x0, y1)
  7575. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7576. # color_t = Color(face_color)
  7577. # color_t.alpha = face_alpha
  7578. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  7579. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  7580. layer=0, tolerance=None)
  7581. if self.is_legacy is True:
  7582. self.move_tool.sel_shapes.redraw()
  7583. def on_file_new_click(self):
  7584. if self.collection.get_list() and self.should_we_save:
  7585. msgbox = QtWidgets.QMessageBox()
  7586. # msgbox.setText("<B>Save changes ...</B>")
  7587. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7588. "Creating a New project will delete them.\n"
  7589. "Do you want to Save the project?"))
  7590. msgbox.setWindowTitle(_("Save changes"))
  7591. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  7592. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7593. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7594. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7595. msgbox.setDefaultButton(bt_yes)
  7596. msgbox.exec_()
  7597. response = msgbox.clickedButton()
  7598. if response == bt_yes:
  7599. self.on_file_saveprojectas()
  7600. elif response == bt_cancel:
  7601. return
  7602. elif response == bt_no:
  7603. self.on_file_new()
  7604. else:
  7605. self.on_file_new()
  7606. self.inform.emit('[success] %s...' %
  7607. _("New Project created"))
  7608. def on_file_new(self, cli=None):
  7609. """
  7610. Callback for menu item File -> New. Returns the application to its
  7611. startup state. This method is thread-safe.
  7612. :return: None
  7613. """
  7614. self.report_usage("on_file_new")
  7615. # Remove everything from memory
  7616. App.log.debug("on_file_new()")
  7617. if self.call_source != 'app':
  7618. self.editor2object(cleanup=True)
  7619. # ## EDITOR section
  7620. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  7621. self.exc_editor = FlatCAMExcEditor(self)
  7622. self.grb_editor = FlatCAMGrbEditor(self)
  7623. # Clear pool
  7624. self.clear_pool()
  7625. for obj in self.collection.get_list():
  7626. # delete shapes left drawn from mark shape_collections, if any
  7627. if isinstance(obj, FlatCAMGerber):
  7628. try:
  7629. obj.mark_shapes.enabled = False
  7630. obj.mark_shapes.clear(update=True)
  7631. except AttributeError:
  7632. pass
  7633. # also delete annotation shapes, if any
  7634. elif isinstance(obj, FlatCAMCNCjob):
  7635. try:
  7636. obj.annotation.enabled = False
  7637. obj.annotation.clear(update=True)
  7638. except AttributeError:
  7639. pass
  7640. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7641. self.init_tcl()
  7642. self.delete_selection_shape()
  7643. self.collection.delete_all()
  7644. self.setup_component_editor()
  7645. # Clear project filename
  7646. self.project_filename = None
  7647. # Load the application defaults
  7648. self.load_defaults(filename='current_defaults')
  7649. # Re-fresh project options
  7650. self.on_options_app2project()
  7651. # Init Tools
  7652. self.init_tools()
  7653. if cli is None:
  7654. # Close any Tabs opened in the Plot Tab Area section
  7655. for index in range(self.ui.plot_tab_area.count()):
  7656. self.ui.plot_tab_area.closeTab(index)
  7657. # for whatever reason previous command does not close the last tab so I do it manually
  7658. self.ui.plot_tab_area.closeTab(0)
  7659. # # And then add again the Plot Area
  7660. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7661. self.ui.plot_tab_area.protectTab(0)
  7662. # take the focus of the Notebook on Project Tab.
  7663. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7664. self.set_ui_title(name=_("New Project - Not saved"))
  7665. def obj_properties(self):
  7666. """
  7667. Will launch the object Properties Tool
  7668. :return:
  7669. """
  7670. self.report_usage("obj_properties()")
  7671. self.properties_tool.run(toggle=False)
  7672. def on_project_context_save(self):
  7673. """
  7674. Wrapper, will save the object function of it's type
  7675. :return:
  7676. """
  7677. obj = self.collection.get_active()
  7678. if type(obj) == FlatCAMGeometry:
  7679. self.on_file_exportdxf()
  7680. elif type(obj) == FlatCAMExcellon:
  7681. self.on_file_saveexcellon()
  7682. elif type(obj) == FlatCAMCNCjob:
  7683. obj.on_exportgcode_button_click()
  7684. elif type(obj) == FlatCAMGerber:
  7685. self.on_file_savegerber()
  7686. elif type(obj) == FlatCAMScript:
  7687. self.on_file_savescript()
  7688. elif type(obj) == FlatCAMDocument:
  7689. self.on_file_savedocument()
  7690. def obj_move(self):
  7691. self.report_usage("obj_move()")
  7692. self.move_tool.run(toggle=False)
  7693. def on_fileopengerber(self, signal: bool = None, name=None):
  7694. """
  7695. File menu callback for opening a Gerber.
  7696. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7697. :return: None
  7698. """
  7699. self.report_usage("on_fileopengerber")
  7700. App.log.debug("on_fileopengerber()")
  7701. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7702. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7703. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  7704. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7705. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7706. "*.mil);;" \
  7707. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7708. "Allegro Files (*.art);;" \
  7709. "Mentor Files (*.pho *.gdo);;" \
  7710. "All Files (*.*)"
  7711. if name is None:
  7712. try:
  7713. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7714. directory=self.get_last_folder(),
  7715. filter=_filter_)
  7716. except TypeError:
  7717. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7718. filenames = [str(filename) for filename in filenames]
  7719. else:
  7720. filenames = [name]
  7721. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7722. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7723. _("Opening Gerber file.")),
  7724. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7725. color=QtGui.QColor("gray"))
  7726. if len(filenames) == 0:
  7727. self.inform.emit('[WARNING_NOTCL] %s' %
  7728. _("Open Gerber cancelled."))
  7729. else:
  7730. for filename in filenames:
  7731. if filename != '':
  7732. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7733. def on_fileopenexcellon(self, signal: bool = None, name=None):
  7734. """
  7735. File menu callback for opening an Excellon file.
  7736. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7737. :return: None
  7738. """
  7739. self.report_usage("on_fileopenexcellon")
  7740. App.log.debug("on_fileopenexcellon()")
  7741. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7742. "All Files (*.*)"
  7743. if name is None:
  7744. try:
  7745. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7746. directory=self.get_last_folder(),
  7747. filter=_filter_)
  7748. except TypeError:
  7749. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7750. filenames = [str(filename) for filename in filenames]
  7751. else:
  7752. filenames = [str(name)]
  7753. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7754. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7755. _("Opening Excellon file.")),
  7756. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7757. color=QtGui.QColor("gray"))
  7758. if len(filenames) == 0:
  7759. self.inform.emit('[WARNING_NOTCL]%s' %
  7760. _(" Open Excellon cancelled."))
  7761. else:
  7762. for filename in filenames:
  7763. if filename != '':
  7764. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7765. def on_fileopengcode(self, signal: bool = None, name=None):
  7766. """
  7767. File menu call back for opening gcode.
  7768. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7769. :return: None
  7770. """
  7771. self.report_usage("on_fileopengcode")
  7772. App.log.debug("on_fileopengcode()")
  7773. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7774. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7775. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  7776. "All Files (*.*)"
  7777. if name is None:
  7778. try:
  7779. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7780. directory=self.get_last_folder(),
  7781. filter=_filter_)
  7782. except TypeError:
  7783. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7784. filenames = [str(filename) for filename in filenames]
  7785. else:
  7786. filenames = [name]
  7787. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7788. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7789. _("Opening G-Code file.")),
  7790. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7791. color=QtGui.QColor("gray"))
  7792. if len(filenames) == 0:
  7793. self.inform.emit('[WARNING_NOTCL] %s' %
  7794. _("Open G-Code cancelled."))
  7795. else:
  7796. for filename in filenames:
  7797. if filename != '':
  7798. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  7799. def on_file_openproject(self, signal: bool = None):
  7800. """
  7801. File menu callback for opening a project.
  7802. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7803. :return: None
  7804. """
  7805. self.report_usage("on_file_openproject")
  7806. App.log.debug("on_file_openproject()")
  7807. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7808. try:
  7809. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7810. directory=self.get_last_folder(), filter=_filter_)
  7811. except TypeError:
  7812. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7813. # The Qt methods above will return a QString which can cause problems later.
  7814. # So far json.dump() will fail to serialize it.
  7815. # TODO: Improve the serialization methods and remove this fix.
  7816. filename = str(filename)
  7817. if filename == "":
  7818. self.inform.emit('[WARNING_NOTCL] %s' %
  7819. _("Open Project cancelled."))
  7820. else:
  7821. # self.worker_task.emit({'fcn': self.open_project,
  7822. # 'params': [filename]})
  7823. # The above was failing because open_project() is not
  7824. # thread safe. The new_project()
  7825. self.open_project(filename)
  7826. def on_fileopenhpgl2(self, signal: bool = None, name=None):
  7827. """
  7828. File menu callback for opening a HPGL2.
  7829. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7830. :return: None
  7831. """
  7832. self.report_usage("on_fileopenhpgl2")
  7833. App.log.debug("on_fileopenhpgl2()")
  7834. _filter_ = "HPGL2 Files (*.plt);;" \
  7835. "All Files (*.*)"
  7836. if name is None:
  7837. try:
  7838. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  7839. directory=self.get_last_folder(),
  7840. filter=_filter_)
  7841. except TypeError:
  7842. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  7843. filenames = [str(filename) for filename in filenames]
  7844. else:
  7845. filenames = [name]
  7846. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7847. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7848. _("Opening HPGL2 file.")),
  7849. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7850. color=QtGui.QColor("gray"))
  7851. if len(filenames) == 0:
  7852. self.inform.emit('[WARNING_NOTCL] %s' % _("Open HPGL2 file cancelled."))
  7853. else:
  7854. for filename in filenames:
  7855. if filename != '':
  7856. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  7857. def on_file_openconfig(self, signal: bool = None):
  7858. """
  7859. File menu callback for opening a config file.
  7860. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7861. :return: None
  7862. """
  7863. self.report_usage("on_file_openconfig")
  7864. App.log.debug("on_file_openconfig()")
  7865. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7866. try:
  7867. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7868. directory=self.data_path, filter=_filter_)
  7869. except TypeError:
  7870. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7871. filter=_filter_)
  7872. if filename == "":
  7873. self.inform.emit('[WARNING_NOTCL] %s' %
  7874. _("Open Config cancelled."))
  7875. else:
  7876. self.open_config_file(filename)
  7877. def on_file_exportsvg(self):
  7878. """
  7879. Callback for menu item File->Export SVG.
  7880. :return: None
  7881. """
  7882. self.report_usage("on_file_exportsvg")
  7883. App.log.debug("on_file_exportsvg()")
  7884. obj = self.collection.get_active()
  7885. if obj is None:
  7886. self.inform.emit('[WARNING_NOTCL] %s' %
  7887. _("No object selected."))
  7888. msg = _("Please Select a Geometry object to export")
  7889. msgbox = QtWidgets.QMessageBox()
  7890. msgbox.setInformativeText(msg)
  7891. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7892. msgbox.setDefaultButton(bt_ok)
  7893. msgbox.exec_()
  7894. return
  7895. # Check for more compatible types and add as required
  7896. if (not isinstance(obj, FlatCAMGeometry)
  7897. and not isinstance(obj, FlatCAMGerber)
  7898. and not isinstance(obj, FlatCAMCNCjob)
  7899. and not isinstance(obj, FlatCAMExcellon)):
  7900. msg = '[ERROR_NOTCL] %s' % \
  7901. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7902. msgbox = QtWidgets.QMessageBox()
  7903. msgbox.setInformativeText(msg)
  7904. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7905. msgbox.setDefaultButton(bt_ok)
  7906. msgbox.exec_()
  7907. return
  7908. name = obj.options["name"]
  7909. _filter = "SVG File (*.svg);;All Files (*.*)"
  7910. try:
  7911. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7912. caption=_("Export SVG"),
  7913. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  7914. filter=_filter)
  7915. except TypeError:
  7916. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  7917. filename = str(filename)
  7918. if filename == "":
  7919. self.inform.emit('[WARNING_NOTCL]%s' %
  7920. _(" Export SVG cancelled."))
  7921. return
  7922. else:
  7923. self.export_svg(name, filename)
  7924. if self.defaults["global_open_style"] is False:
  7925. self.file_opened.emit("SVG", filename)
  7926. self.file_saved.emit("SVG", filename)
  7927. def on_file_exportpng(self):
  7928. self.report_usage("on_file_exportpng")
  7929. App.log.debug("on_file_exportpng()")
  7930. self.date = str(datetime.today()).rpartition('.')[0]
  7931. self.date = ''.join(c for c in self.date if c not in ':-')
  7932. self.date = self.date.replace(' ', '_')
  7933. if self.is_legacy is False:
  7934. image = _screenshot()
  7935. data = np.asarray(image)
  7936. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7937. self.inform.emit('[[WARNING_NOTCL]] %s' %
  7938. _('Data must be a 3D array with last dimension 3 or 4'))
  7939. return
  7940. filter_ = "PNG File (*.png);;All Files (*.*)"
  7941. try:
  7942. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7943. caption=_("Export PNG Image"),
  7944. directory=self.get_last_save_folder() + '/png_' + self.date,
  7945. filter=filter_)
  7946. except TypeError:
  7947. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  7948. filename = str(filename)
  7949. if filename == "":
  7950. self.inform.emit(_("Export PNG cancelled."))
  7951. return
  7952. else:
  7953. if self.is_legacy is False:
  7954. write_png(filename, data)
  7955. else:
  7956. self.plotcanvas.figure.savefig(filename)
  7957. if self.defaults["global_open_style"] is False:
  7958. self.file_opened.emit("png", filename)
  7959. self.file_saved.emit("png", filename)
  7960. def on_file_savegerber(self):
  7961. """
  7962. Callback for menu item in Project context menu.
  7963. :return: None
  7964. """
  7965. self.report_usage("on_file_savegerber")
  7966. App.log.debug("on_file_savegerber()")
  7967. obj = self.collection.get_active()
  7968. if obj is None:
  7969. self.inform.emit('[WARNING_NOTCL] %s' %
  7970. _("No object selected. Please select an Gerber object to export."))
  7971. return
  7972. # Check for more compatible types and add as required
  7973. if not isinstance(obj, FlatCAMGerber):
  7974. self.inform.emit('[ERROR_NOTCL] %s' %
  7975. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7976. return
  7977. name = self.collection.get_active().options["name"]
  7978. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7979. try:
  7980. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7981. caption="Save Gerber source file",
  7982. directory=self.get_last_save_folder() + '/' + name,
  7983. filter=_filter)
  7984. except TypeError:
  7985. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7986. filename = str(filename)
  7987. if filename == "":
  7988. self.inform.emit('[WARNING_NOTCL] %s' %
  7989. _("Save Gerber source file cancelled."))
  7990. return
  7991. else:
  7992. self.save_source_file(name, filename)
  7993. if self.defaults["global_open_style"] is False:
  7994. self.file_opened.emit("Gerber", filename)
  7995. self.file_saved.emit("Gerber", filename)
  7996. def on_file_savescript(self):
  7997. """
  7998. Callback for menu item in Project context menu.
  7999. :return: None
  8000. """
  8001. self.report_usage("on_file_savescript")
  8002. App.log.debug("on_file_savescript()")
  8003. obj = self.collection.get_active()
  8004. if obj is None:
  8005. self.inform.emit('[WARNING_NOTCL] %s' %
  8006. _("No object selected. Please select an Script object to export."))
  8007. return
  8008. # Check for more compatible types and add as required
  8009. if not isinstance(obj, FlatCAMScript):
  8010. self.inform.emit('[ERROR_NOTCL] %s' %
  8011. _("Failed. Only Script objects can be saved as TCL Script files..."))
  8012. return
  8013. name = self.collection.get_active().options["name"]
  8014. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  8015. try:
  8016. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8017. caption="Save Script source file",
  8018. directory=self.get_last_save_folder() + '/' + name,
  8019. filter=_filter)
  8020. except TypeError:
  8021. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Script source file"), filter=_filter)
  8022. filename = str(filename)
  8023. if filename == "":
  8024. self.inform.emit('[WARNING_NOTCL] %s' %
  8025. _("Save Script source file cancelled."))
  8026. return
  8027. else:
  8028. self.save_source_file(name, filename)
  8029. if self.defaults["global_open_style"] is False:
  8030. self.file_opened.emit("Script", filename)
  8031. self.file_saved.emit("Script", filename)
  8032. def on_file_savedocument(self):
  8033. """
  8034. Callback for menu item in Project context menu.
  8035. :return: None
  8036. """
  8037. self.report_usage("on_file_savedocument")
  8038. App.log.debug("on_file_savedocument()")
  8039. obj = self.collection.get_active()
  8040. if obj is None:
  8041. self.inform.emit('[WARNING_NOTCL] %s' %
  8042. _("No object selected. Please select an Document object to export."))
  8043. return
  8044. # Check for more compatible types and add as required
  8045. if not isinstance(obj, FlatCAMScript):
  8046. self.inform.emit('[ERROR_NOTCL] %s' %
  8047. _("Failed. Only Document objects can be saved as Document files..."))
  8048. return
  8049. name = self.collection.get_active().options["name"]
  8050. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  8051. try:
  8052. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8053. caption="Save Document source file",
  8054. directory=self.get_last_save_folder() + '/' + name,
  8055. filter=_filter)
  8056. except TypeError:
  8057. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Document source file"), filter=_filter)
  8058. filename = str(filename)
  8059. if filename == "":
  8060. self.inform.emit('[WARNING_NOTCL] %s' %
  8061. _("Save Document source file cancelled."))
  8062. return
  8063. else:
  8064. self.save_source_file(name, filename)
  8065. if self.defaults["global_open_style"] is False:
  8066. self.file_opened.emit("Document", filename)
  8067. self.file_saved.emit("Document", filename)
  8068. def on_file_saveexcellon(self):
  8069. """
  8070. Callback for menu item in project context menu.
  8071. :return: None
  8072. """
  8073. self.report_usage("on_file_saveexcellon")
  8074. App.log.debug("on_file_saveexcellon()")
  8075. obj = self.collection.get_active()
  8076. if obj is None:
  8077. self.inform.emit('[WARNING_NOTCL] %s' %
  8078. _("No object selected. Please select an Excellon object to export."))
  8079. return
  8080. # Check for more compatible types and add as required
  8081. if not isinstance(obj, FlatCAMExcellon):
  8082. self.inform.emit('[ERROR_NOTCL] %s' %
  8083. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  8084. return
  8085. name = self.collection.get_active().options["name"]
  8086. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  8087. try:
  8088. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8089. caption=_("Save Excellon source file"),
  8090. directory=self.get_last_save_folder() + '/' + name,
  8091. filter=_filter)
  8092. except TypeError:
  8093. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  8094. filename = str(filename)
  8095. if filename == "":
  8096. self.inform.emit('[WARNING_NOTCL] %s' %
  8097. _("Saving Excellon source file cancelled."))
  8098. return
  8099. else:
  8100. self.save_source_file(name, filename)
  8101. if self.defaults["global_open_style"] is False:
  8102. self.file_opened.emit("Excellon", filename)
  8103. self.file_saved.emit("Excellon", filename)
  8104. def on_file_exportexcellon(self):
  8105. """
  8106. Callback for menu item File->Export->Excellon.
  8107. :return: None
  8108. """
  8109. self.report_usage("on_file_exportexcellon")
  8110. App.log.debug("on_file_exportexcellon()")
  8111. obj = self.collection.get_active()
  8112. if obj is None:
  8113. self.inform.emit('[WARNING_NOTCL] %s' %
  8114. _("No object selected. Please Select an Excellon object to export."))
  8115. return
  8116. # Check for more compatible types and add as required
  8117. if not isinstance(obj, FlatCAMExcellon):
  8118. self.inform.emit('[ERROR_NOTCL] %s' %
  8119. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  8120. return
  8121. name = self.collection.get_active().options["name"]
  8122. _filter = self.defaults["excellon_save_filters"]
  8123. try:
  8124. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8125. caption=_("Export Excellon"),
  8126. directory=self.get_last_save_folder() + '/' + name,
  8127. filter=_filter)
  8128. except TypeError:
  8129. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  8130. filename = str(filename)
  8131. if filename == "":
  8132. self.inform.emit('[WARNING_NOTCL] %s' %
  8133. _("Export Excellon cancelled."))
  8134. return
  8135. else:
  8136. used_extension = filename.rpartition('.')[2]
  8137. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  8138. self.export_excellon(name, filename)
  8139. if self.defaults["global_open_style"] is False:
  8140. self.file_opened.emit("Excellon", filename)
  8141. self.file_saved.emit("Excellon", filename)
  8142. def on_file_exportgerber(self):
  8143. """
  8144. Callback for menu item File->Export->Gerber.
  8145. :return: None
  8146. """
  8147. self.report_usage("on_file_exportgerber")
  8148. App.log.debug("on_file_exportgerber()")
  8149. obj = self.collection.get_active()
  8150. if obj is None:
  8151. self.inform.emit('[WARNING_NOTCL] %s' %
  8152. _("No object selected. Please Select an Gerber object to export."))
  8153. return
  8154. # Check for more compatible types and add as required
  8155. if not isinstance(obj, FlatCAMGerber):
  8156. self.inform.emit('[ERROR_NOTCL] %s' %
  8157. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  8158. return
  8159. name = self.collection.get_active().options["name"]
  8160. _filter_ = self.defaults['gerber_save_filters']
  8161. try:
  8162. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8163. caption=_("Export Gerber"),
  8164. directory=self.get_last_save_folder() + '/' + name,
  8165. filter=_filter_)
  8166. except TypeError:
  8167. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  8168. filename = str(filename)
  8169. if filename == "":
  8170. self.inform.emit('[WARNING_NOTCL] %s' %
  8171. _("Export Gerber cancelled."))
  8172. return
  8173. else:
  8174. used_extension = filename.rpartition('.')[2]
  8175. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  8176. self.export_gerber(name, filename)
  8177. if self.defaults["global_open_style"] is False:
  8178. self.file_opened.emit("Gerber", filename)
  8179. self.file_saved.emit("Gerber", filename)
  8180. def on_file_exportdxf(self):
  8181. """
  8182. Callback for menu item File->Export DXF.
  8183. :return: None
  8184. """
  8185. self.report_usage("on_file_exportdxf")
  8186. App.log.debug("on_file_exportdxf()")
  8187. obj = self.collection.get_active()
  8188. if obj is None:
  8189. self.inform.emit('[WARNING_NOTCL] %s' %
  8190. _("No object selected."))
  8191. msg = _("Please Select a Geometry object to export")
  8192. msgbox = QtWidgets.QMessageBox()
  8193. msgbox.setInformativeText(msg)
  8194. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8195. msgbox.setDefaultButton(bt_ok)
  8196. msgbox.exec_()
  8197. return
  8198. # Check for more compatible types and add as required
  8199. if not isinstance(obj, FlatCAMGeometry):
  8200. msg = '[ERROR_NOTCL] %s' % \
  8201. _("Only Geometry objects can be used.")
  8202. msgbox = QtWidgets.QMessageBox()
  8203. msgbox.setInformativeText(msg)
  8204. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8205. msgbox.setDefaultButton(bt_ok)
  8206. msgbox.exec_()
  8207. return
  8208. name = self.collection.get_active().options["name"]
  8209. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8210. try:
  8211. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8212. caption=_("Export DXF"),
  8213. directory=self.get_last_save_folder() + '/' + name,
  8214. filter=_filter_)
  8215. except TypeError:
  8216. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  8217. filter=_filter_)
  8218. filename = str(filename)
  8219. if filename == "":
  8220. self.inform.emit('[WARNING_NOTCL] %s' %
  8221. _("Export DXF cancelled."))
  8222. return
  8223. else:
  8224. self.export_dxf(name, filename)
  8225. if self.defaults["global_open_style"] is False:
  8226. self.file_opened.emit("DXF", filename)
  8227. self.file_saved.emit("DXF", filename)
  8228. def on_file_importsvg(self, type_of_obj):
  8229. """
  8230. Callback for menu item File->Import SVG.
  8231. :param type_of_obj: to import the SVG as Geometry or as Gerber
  8232. :type type_of_obj: str
  8233. :return: None
  8234. """
  8235. self.report_usage("on_file_importsvg")
  8236. App.log.debug("on_file_importsvg()")
  8237. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  8238. try:
  8239. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8240. directory=self.get_last_folder(), filter=_filter_)
  8241. except TypeError:
  8242. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8243. filter=_filter_)
  8244. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8245. type_of_obj = "geometry"
  8246. filenames = [str(filename) for filename in filenames]
  8247. if len(filenames) == 0:
  8248. self.inform.emit('[WARNING_NOTCL] %s' %
  8249. _("Open SVG cancelled."))
  8250. else:
  8251. for filename in filenames:
  8252. if filename != '':
  8253. self.worker_task.emit({'fcn': self.import_svg,
  8254. 'params': [filename, type_of_obj]})
  8255. def on_file_importdxf(self, type_of_obj):
  8256. """
  8257. Callback for menu item File->Import DXF.
  8258. :param type_of_obj: to import the DXF as Geometry or as Gerber
  8259. :type type_of_obj: str
  8260. :return: None
  8261. """
  8262. self.report_usage("on_file_importdxf")
  8263. App.log.debug("on_file_importdxf()")
  8264. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8265. try:
  8266. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8267. directory=self.get_last_folder(),
  8268. filter=_filter_)
  8269. except TypeError:
  8270. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8271. filter=_filter_)
  8272. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8273. type_of_obj = "geometry"
  8274. filenames = [str(filename) for filename in filenames]
  8275. if len(filenames) == 0:
  8276. self.inform.emit('[WARNING_NOTCL] %s' %
  8277. _("Open DXF cancelled."))
  8278. else:
  8279. for filename in filenames:
  8280. if filename != '':
  8281. self.worker_task.emit({'fcn': self.import_dxf,
  8282. 'params': [filename, type_of_obj]})
  8283. # ###############################################################################################################
  8284. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  8285. # ###############################################################################################################
  8286. def init_code_editor(self, name):
  8287. self.text_editor_tab = TextEditor(app=self)
  8288. # add the tab if it was closed
  8289. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  8290. self.text_editor_tab.setObjectName('text_editor_tab')
  8291. # delete the absolute and relative position and messages in the infobar
  8292. self.ui.position_label.setText("")
  8293. self.ui.rel_position_label.setText("")
  8294. # first clear previous text in text editor (if any)
  8295. self.text_editor_tab.code_editor.clear()
  8296. self.text_editor_tab.code_editor.setReadOnly(False)
  8297. self.toggle_codeeditor = True
  8298. self.text_editor_tab.code_editor.completer_enable = False
  8299. self.text_editor_tab.buttonRun.hide()
  8300. # make sure to keep a reference to the code editor
  8301. self.reference_code_editor = self.text_editor_tab.code_editor
  8302. # Switch plot_area to CNCJob tab
  8303. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  8304. def on_view_source(self):
  8305. """
  8306. Called when the user wants to see the source file of the selected object
  8307. :return:
  8308. """
  8309. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  8310. self.proc_container.view.set_busy(_("Loading..."))
  8311. try:
  8312. obj = self.collection.get_active()
  8313. except Exception as e:
  8314. log.debug("App.on_view_source() --> %s" % str(e))
  8315. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8316. return 'fail'
  8317. if obj is None:
  8318. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8319. return 'fail'
  8320. flt = "All Files (*.*)"
  8321. if obj.kind == 'gerber':
  8322. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  8323. elif obj.kind == 'excellon':
  8324. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  8325. elif obj.kind == 'cncjob':
  8326. "GCode Files (*.NC);;All Files (*.*)"
  8327. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  8328. # add the tab if it was closed
  8329. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  8330. self.source_editor_tab.setObjectName('source_editor_tab')
  8331. # delete the absolute and relative position and messages in the infobar
  8332. self.ui.position_label.setText("")
  8333. self.ui.rel_position_label.setText("")
  8334. # first clear previous text in text editor (if any)
  8335. self.source_editor_tab.code_editor.clear()
  8336. self.source_editor_tab.code_editor.setReadOnly(False)
  8337. self.source_editor_tab.code_editor.completer_enable = False
  8338. self.source_editor_tab.buttonRun.hide()
  8339. # Switch plot_area to CNCJob tab
  8340. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  8341. try:
  8342. self.source_editor_tab.buttonOpen.clicked.disconnect()
  8343. except TypeError:
  8344. pass
  8345. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  8346. try:
  8347. self.source_editor_tab.buttonSave.clicked.disconnect()
  8348. except TypeError:
  8349. pass
  8350. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  8351. # then append the text from GCode to the text editor
  8352. if obj.kind == 'cncjob':
  8353. try:
  8354. file = obj.export_gcode(
  8355. preamble=self.defaults["cncjob_prepend"],
  8356. postamble=self.defaults["cncjob_append"],
  8357. to_file=True)
  8358. if file == 'fail':
  8359. return 'fail'
  8360. except AttributeError:
  8361. self.inform.emit('[WARNING_NOTCL] %s' %
  8362. _("There is no selected object for which to see it's source file code."))
  8363. return 'fail'
  8364. else:
  8365. try:
  8366. file = StringIO(obj.source_file)
  8367. except (AttributeError, TypeError):
  8368. self.inform.emit('[WARNING_NOTCL] %s' %
  8369. _("There is no selected object for which to see it's source file code."))
  8370. return 'fail'
  8371. self.source_editor_tab.t_frame.hide()
  8372. try:
  8373. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  8374. # for line in file:
  8375. # QtWidgets.QApplication.processEvents()
  8376. # proc_line = str(line).strip('\n')
  8377. # self.source_editor_tab.code_editor.append(proc_line)
  8378. except Exception as e:
  8379. log.debug('App.on_view_source() -->%s' % str(e))
  8380. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  8381. return
  8382. self.source_editor_tab.handleTextChanged()
  8383. self.source_editor_tab.t_frame.show()
  8384. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  8385. self.proc_container.view.set_idle()
  8386. # self.ui.show()
  8387. def on_toggle_code_editor(self):
  8388. self.report_usage("on_toggle_code_editor()")
  8389. if self.toggle_codeeditor is False:
  8390. self.init_code_editor(name=_("Code Editor"))
  8391. self.text_editor_tab.buttonOpen.clicked.disconnect()
  8392. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  8393. self.text_editor_tab.buttonSave.clicked.disconnect()
  8394. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  8395. else:
  8396. for idx in range(self.ui.plot_tab_area.count()):
  8397. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  8398. self.ui.plot_tab_area.closeTab(idx)
  8399. break
  8400. self.toggle_codeeditor = False
  8401. def on_code_editor_close(self):
  8402. print("closed")
  8403. self.toggle_codeeditor = False
  8404. def on_filenewscript(self, silent=False, name=None, text=None):
  8405. """
  8406. Will create a new script file and open it in the Code Editor
  8407. :param silent: if True will not display status messages
  8408. :param name: if specified will be the name of the new script
  8409. :param text: pass a source file to the newly created script to be loaded in it
  8410. :return: None
  8411. """
  8412. if silent is False:
  8413. self.inform.emit('[success] %s' %
  8414. _("New TCL script file created in Code Editor."))
  8415. # delete the absolute and relative position and messages in the infobar
  8416. self.ui.position_label.setText("")
  8417. self.ui.rel_position_label.setText("")
  8418. if name is not None:
  8419. self.new_script_object(name=name, text=text)
  8420. else:
  8421. self.new_script_object(text=text)
  8422. # script_text = script_obj.source_file
  8423. #
  8424. # self.proc_container.view.set_busy(_("Loading..."))
  8425. # script_obj.script_editor_tab.t_frame.hide()
  8426. #
  8427. # script_obj.script_editor_tab.t_frame.show()
  8428. # self.proc_container.view.set_idle()
  8429. def on_fileopenscript(self, name=None, silent=False):
  8430. """
  8431. Will open a Tcl script file into the Code Editor
  8432. :param silent: if True will not display status messages
  8433. :param name: name of a Tcl script file to open
  8434. :return:
  8435. """
  8436. self.report_usage("on_fileopenscript")
  8437. App.log.debug("on_fileopenscript()")
  8438. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8439. if name:
  8440. filenames = [name]
  8441. else:
  8442. try:
  8443. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  8444. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  8445. except TypeError:
  8446. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  8447. if len(filenames) == 0:
  8448. if silent is False:
  8449. self.inform.emit('[WARNING_NOTCL] %s' % _("Open TCL script cancelled."))
  8450. else:
  8451. for filename in filenames:
  8452. if filename != '':
  8453. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  8454. def on_filerunscript(self, name=None, silent=False):
  8455. """
  8456. File menu callback for loading and running a TCL script.
  8457. :param silent: if True will not display status messages
  8458. :param name: name of a Tcl script file to be run by FlatCAM
  8459. :return: None
  8460. """
  8461. self.report_usage("on_filerunscript")
  8462. App.log.debug("on_file_runscript()")
  8463. if name:
  8464. filename = name
  8465. if self.cmd_line_headless != 1:
  8466. self.splash.showMessage('%s: %ssec\n%s' %
  8467. (_("Canvas initialization started.\n"
  8468. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8469. _("Executing FlatCAMScript file.")
  8470. ),
  8471. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8472. color=QtGui.QColor("gray"))
  8473. else:
  8474. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8475. try:
  8476. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  8477. directory=self.get_last_folder(), filter=_filter_)
  8478. except TypeError:
  8479. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  8480. # The Qt methods above will return a QString which can cause problems later.
  8481. # So far json.dump() will fail to serialize it.
  8482. # TODO: Improve the serialization methods and remove this fix.
  8483. filename = str(filename)
  8484. if filename == "":
  8485. if silent is False:
  8486. self.inform.emit('[WARNING_NOTCL] %s' %
  8487. _("Run TCL script cancelled."))
  8488. else:
  8489. if self.cmd_line_headless != 1:
  8490. if self.ui.shell_dock.isHidden():
  8491. self.ui.shell_dock.show()
  8492. try:
  8493. with open(filename, "r") as tcl_script:
  8494. cmd_line_shellfile_content = tcl_script.read()
  8495. if self.cmd_line_headless != 1:
  8496. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  8497. else:
  8498. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  8499. if silent is False:
  8500. self.inform.emit('[success] %s' %
  8501. _("TCL script file opened in Code Editor and executed."))
  8502. except Exception as e:
  8503. log.debug("App.on_filerunscript() -> %s" % str(e))
  8504. sys.exit(2)
  8505. def on_file_saveproject(self, silent=False):
  8506. """
  8507. Callback for menu item File->Save Project. Saves the project to
  8508. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  8509. if set to None. The project is saved by calling ``self.save_project()``.
  8510. :param silent: if True will not display status messages
  8511. :return: None
  8512. """
  8513. self.report_usage("on_file_saveproject")
  8514. if self.project_filename is None:
  8515. self.on_file_saveprojectas()
  8516. else:
  8517. self.worker_task.emit({'fcn': self.save_project,
  8518. 'params': [self.project_filename, silent]})
  8519. if self.defaults["global_open_style"] is False:
  8520. self.file_opened.emit("project", self.project_filename)
  8521. self.file_saved.emit("project", self.project_filename)
  8522. self.set_ui_title(name=self.project_filename)
  8523. self.should_we_save = False
  8524. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  8525. """
  8526. Callback for menu item File->Save Project As... Opens a file
  8527. chooser and saves the project to the given file via
  8528. ``self.save_project()``.
  8529. :param make_copy if to be create a copy of the project; boolean
  8530. :param use_thread: if to be run in a separate thread; boolean
  8531. :param quit_action: if to be followed by quiting the application; boolean
  8532. :return: None
  8533. """
  8534. self.report_usage("on_file_saveprojectas")
  8535. self.date = str(datetime.today()).rpartition('.')[0]
  8536. self.date = ''.join(c for c in self.date if c not in ':-')
  8537. self.date = self.date.replace(' ', '_')
  8538. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  8539. try:
  8540. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8541. caption=_("Save Project As ..."),
  8542. directory=('{l_save}/{proj}_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date,
  8543. proj=_("Project")),
  8544. filter=filter_
  8545. )
  8546. except TypeError:
  8547. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  8548. filename = str(filename)
  8549. if filename == '':
  8550. self.inform.emit('[WARNING_NOTCL] %s' % _("Save Project cancelled."))
  8551. return
  8552. try:
  8553. f = open(filename, 'r')
  8554. f.close()
  8555. except IOError:
  8556. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8557. return
  8558. if use_thread is True:
  8559. self.worker_task.emit({'fcn': self.save_project,
  8560. 'params': [filename, quit_action]})
  8561. else:
  8562. self.save_project(filename, quit_action)
  8563. # self.save_project(filename)
  8564. if self.defaults["global_open_style"] is False:
  8565. self.file_opened.emit("project", filename)
  8566. self.file_saved.emit("project", filename)
  8567. if not make_copy:
  8568. self.project_filename = filename
  8569. self.set_ui_title(name=self.project_filename)
  8570. self.should_we_save = False
  8571. def on_file_save_object_pdf(self, use_thread=True):
  8572. self.date = str(datetime.today()).rpartition('.')[0]
  8573. self.date = ''.join(c for c in self.date if c not in ':-')
  8574. self.date = self.date.replace(' ', '_')
  8575. try:
  8576. obj_active = self.collection.get_active()
  8577. obj_name = _(str(obj_active.options['name']))
  8578. except AttributeError as err:
  8579. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  8580. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  8581. return
  8582. filter_ = "PDF File (*.PDF);; All Files (*.*)"
  8583. try:
  8584. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8585. caption=_("Save Object as PDF ..."),
  8586. directory=('{l_save}/{obj_name}_{date}').format(l_save=str(self.get_last_save_folder()),
  8587. obj_name=obj_name,
  8588. date=self.date),
  8589. filter=filter_
  8590. )
  8591. except TypeError:
  8592. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Object as PDF ..."), filter=filter_)
  8593. filename = str(filename)
  8594. if filename == '':
  8595. self.inform.emit('[WARNING_NOTCL] %s' % _("Save Object PDF cancelled."))
  8596. return
  8597. if use_thread is True:
  8598. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_name]})
  8599. else:
  8600. self.save_pdf(filename, obj_name)
  8601. # self.save_project(filename)
  8602. if self.defaults["global_open_style"] is False:
  8603. self.file_opened.emit("pdf", filename)
  8604. self.file_saved.emit("pdf", filename)
  8605. def save_pdf(self, file_name, obj_name):
  8606. self.film_tool.export_positive(obj_name=obj_name, box_name=obj_name, filename=file_name, ftype='pdf')
  8607. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  8608. """
  8609. Exports a Geometry Object to an SVG file.
  8610. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8611. :param filename: Path to the SVG file to save to.
  8612. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  8613. :return:
  8614. """
  8615. self.report_usage("export_svg()")
  8616. if filename is None:
  8617. filename = self.defaults["global_last_save_folder"]
  8618. self.log.debug("export_svg()")
  8619. try:
  8620. obj = self.collection.get_by_name(str(obj_name))
  8621. except Exception:
  8622. # TODO: The return behavior has not been established... should raise exception?
  8623. return "Could not retrieve object: %s" % obj_name
  8624. with self.proc_container.new(_("Exporting SVG")) as proc:
  8625. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  8626. # Determine bounding area for svg export
  8627. bounds = obj.bounds()
  8628. size = obj.size()
  8629. # Convert everything to strings for use in the xml doc
  8630. svgwidth = str(size[0])
  8631. svgheight = str(size[1])
  8632. minx = str(bounds[0])
  8633. miny = str(bounds[1] - size[1])
  8634. uom = obj.units.lower()
  8635. # Add a SVG Header and footer to the svg output from shapely
  8636. # The transform flips the Y Axis so that everything renders
  8637. # properly within svg apps such as inkscape
  8638. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8639. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8640. svg_header += 'width="' + svgwidth + uom + '" '
  8641. svg_header += 'height="' + svgheight + uom + '" '
  8642. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  8643. svg_header += '<g transform="scale(1,-1)">'
  8644. svg_footer = '</g> </svg>'
  8645. svg_elem = svg_header + exported_svg + svg_footer
  8646. # Parse the xml through a xml parser just to add line feeds
  8647. # and to make it look more pretty for the output
  8648. svgcode = parse_xml_string(svg_elem)
  8649. svgcode = svgcode.toprettyxml()
  8650. try:
  8651. with open(filename, 'w') as fp:
  8652. fp.write(svgcode)
  8653. except PermissionError:
  8654. self.inform.emit('[WARNING] %s' %
  8655. _("Permission denied, saving not possible.\n"
  8656. "Most likely another app is holding the file open and not accessible."))
  8657. return 'fail'
  8658. if self.defaults["global_open_style"] is False:
  8659. self.file_opened.emit("SVG", filename)
  8660. self.file_saved.emit("SVG", filename)
  8661. self.inform.emit('[success] %s: %s' %
  8662. (_("SVG file exported to"), filename))
  8663. def save_source_file(self, obj_name, filename, use_thread=True):
  8664. """
  8665. Exports a FlatCAM Object to an Gerber/Excellon file.
  8666. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8667. :param filename: Path to the Gerber file to save to.
  8668. :param use_thread: if to be run in a separate thread
  8669. :return:
  8670. """
  8671. self.report_usage("save source file()")
  8672. if filename is None:
  8673. filename = self.defaults["global_last_save_folder"]
  8674. self.log.debug("save source file()")
  8675. obj = self.collection.get_by_name(obj_name)
  8676. file_string = StringIO(obj.source_file)
  8677. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8678. if file_string.getvalue() == '':
  8679. self.inform.emit('[ERROR_NOTCL] %s' %
  8680. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  8681. return 'fail'
  8682. try:
  8683. with open(filename, 'w') as file:
  8684. file.writelines('G04*\n')
  8685. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8686. (obj.kind.upper(), str(self.version), str(self.version_date)))
  8687. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8688. file.writelines('G04 Created on : %s*\n' % time_string)
  8689. for line in file_string:
  8690. file.writelines(line)
  8691. except PermissionError:
  8692. self.inform.emit('[WARNING] %s' %
  8693. _("Permission denied, saving not possible.\n"
  8694. "Most likely another app is holding the file open and not accessible."))
  8695. return 'fail'
  8696. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  8697. """
  8698. Exports a Excellon Object to an Excellon file.
  8699. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  8700. :param filename: Path to the Excellon file to save to.
  8701. :param local_use:
  8702. :param use_thread: if to be run in a separate thread
  8703. :return:
  8704. """
  8705. self.report_usage("export_excellon()")
  8706. if filename is None:
  8707. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  8708. self.log.debug("export_excellon()")
  8709. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  8710. self.defaults["excellon_exp_decimals"]
  8711. )
  8712. if local_use is None:
  8713. try:
  8714. obj = self.collection.get_by_name(str(obj_name))
  8715. except Exception:
  8716. # TODO: The return behavior has not been established... should raise exception?
  8717. return "Could not retrieve object: %s" % obj_name
  8718. else:
  8719. obj = local_use
  8720. if not isinstance(obj, FlatCAMExcellon):
  8721. self.inform.emit('[ERROR_NOTCL] %s' %
  8722. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  8723. return
  8724. # updated units
  8725. eunits = self.defaults["excellon_exp_units"]
  8726. ewhole = self.defaults["excellon_exp_integer"]
  8727. efract = self.defaults["excellon_exp_decimals"]
  8728. ezeros = self.defaults["excellon_exp_zeros"]
  8729. eformat = self.defaults["excellon_exp_format"]
  8730. slot_type = self.defaults["excellon_exp_slot_type"]
  8731. fc_units = self.defaults['units'].upper()
  8732. if fc_units == 'MM':
  8733. factor = 1 if eunits == 'METRIC' else 0.03937
  8734. else:
  8735. factor = 25.4 if eunits == 'METRIC' else 1
  8736. def make_excellon():
  8737. try:
  8738. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8739. header = 'M48\n'
  8740. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  8741. (str(self.version), str(self.version_date))
  8742. header += ';Filename: %s' % str(obj_name) + '\n'
  8743. header += ';Created on : %s' % time_str + '\n'
  8744. if eformat == 'dec':
  8745. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  8746. header += eunits + '\n'
  8747. for tool in obj.tools:
  8748. if eunits == 'METRIC':
  8749. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8750. tool=str(tool),
  8751. dec=2)
  8752. else:
  8753. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8754. tool=str(tool),
  8755. dec=4)
  8756. else:
  8757. if ezeros == 'LZ':
  8758. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8759. form='ndec', e_zeros='LZ', factor=factor,
  8760. slot_type=slot_type)
  8761. header += '%s,%s\n' % (eunits, 'LZ')
  8762. header += format_exc
  8763. for tool in obj.tools:
  8764. if eunits == 'METRIC':
  8765. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8766. tool=str(tool),
  8767. dec=2)
  8768. else:
  8769. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8770. tool=str(tool),
  8771. dec=4)
  8772. else:
  8773. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8774. form='ndec', e_zeros='TZ', factor=factor,
  8775. slot_type=slot_type)
  8776. header += '%s,%s\n' % (eunits, 'TZ')
  8777. header += format_exc
  8778. for tool in obj.tools:
  8779. if eunits == 'METRIC':
  8780. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8781. tool=str(tool),
  8782. dec=2)
  8783. else:
  8784. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8785. tool=str(tool),
  8786. dec=4)
  8787. header += '%\n'
  8788. footer = 'M30\n'
  8789. exported_excellon = header
  8790. exported_excellon += excellon_code
  8791. exported_excellon += footer
  8792. if local_use is None:
  8793. try:
  8794. with open(filename, 'w') as fp:
  8795. fp.write(exported_excellon)
  8796. except PermissionError:
  8797. self.inform.emit('[WARNING] %s' %
  8798. _("Permission denied, saving not possible.\n"
  8799. "Most likely another app is holding the file open and not accessible."))
  8800. return 'fail'
  8801. if self.defaults["global_open_style"] is False:
  8802. self.file_opened.emit("Excellon", filename)
  8803. self.file_saved.emit("Excellon", filename)
  8804. self.inform.emit('[success] %s: %s' %
  8805. (_("Excellon file exported to"), filename))
  8806. else:
  8807. return exported_excellon
  8808. except Exception as e:
  8809. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8810. return 'fail'
  8811. if use_thread is True:
  8812. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8813. def job_thread_exc(app_obj):
  8814. ret = make_excellon()
  8815. if ret == 'fail':
  8816. self.inform.emit('[ERROR_NOTCL] %s' %
  8817. _('Could not export Excellon file.'))
  8818. return
  8819. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8820. else:
  8821. ret = make_excellon()
  8822. if ret == 'fail':
  8823. self.inform.emit('[ERROR_NOTCL] %s' %
  8824. _('Could not export Excellon file.'))
  8825. return 'fail'
  8826. if local_use is not None:
  8827. return ret
  8828. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8829. """
  8830. Exports a Gerber Object to an Gerber file.
  8831. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8832. :param filename: Path to the Gerber file to save to.
  8833. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8834. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8835. :param use_thread: if to be run in a separate thread
  8836. :return:
  8837. """
  8838. self.report_usage("export_gerber()")
  8839. if filename is None:
  8840. filename = self.defaults["global_last_save_folder"]
  8841. self.log.debug("export_gerber()")
  8842. if local_use is None:
  8843. try:
  8844. obj = self.collection.get_by_name(str(obj_name))
  8845. except Exception:
  8846. # TODO: The return behavior has not been established... should raise exception?
  8847. return "Could not retrieve object: %s" % obj_name
  8848. else:
  8849. obj = local_use
  8850. # updated units
  8851. gunits = self.defaults["gerber_exp_units"]
  8852. gwhole = self.defaults["gerber_exp_integer"]
  8853. gfract = self.defaults["gerber_exp_decimals"]
  8854. gzeros = self.defaults["gerber_exp_zeros"]
  8855. fc_units = self.defaults['units'].upper()
  8856. if fc_units == 'MM':
  8857. factor = 1 if gunits == 'MM' else 0.03937
  8858. else:
  8859. factor = 25.4 if gunits == 'MM' else 1
  8860. def make_gerber():
  8861. try:
  8862. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8863. header = 'G04*\n'
  8864. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8865. (str(self.version), str(self.version_date))
  8866. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8867. header += 'G04 Created on : %s*' % time_str + '\n'
  8868. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8869. header += "%MO{units}*%\n".format(units=gunits)
  8870. for apid in obj.apertures:
  8871. if obj.apertures[apid]['type'] == 'C':
  8872. header += "%ADD{apid}{type},{size}*%\n".format(
  8873. apid=str(apid),
  8874. type='C',
  8875. size=(factor * obj.apertures[apid]['size'])
  8876. )
  8877. elif obj.apertures[apid]['type'] == 'R':
  8878. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8879. apid=str(apid),
  8880. type='R',
  8881. width=(factor * obj.apertures[apid]['width']),
  8882. height=(factor * obj.apertures[apid]['height'])
  8883. )
  8884. elif obj.apertures[apid]['type'] == 'O':
  8885. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8886. apid=str(apid),
  8887. type='O',
  8888. width=(factor * obj.apertures[apid]['width']),
  8889. height=(factor * obj.apertures[apid]['height'])
  8890. )
  8891. header += '\n'
  8892. # obsolete units but some software may need it
  8893. if gunits == 'IN':
  8894. header += 'G70*\n'
  8895. else:
  8896. header += 'G71*\n'
  8897. # Absolute Mode
  8898. header += 'G90*\n'
  8899. header += 'G01*\n'
  8900. # positive polarity
  8901. header += '%LPD*%\n'
  8902. footer = 'M02*\n'
  8903. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8904. exported_gerber = header
  8905. exported_gerber += gerber_code
  8906. exported_gerber += footer
  8907. if local_use is None:
  8908. try:
  8909. with open(filename, 'w') as fp:
  8910. fp.write(exported_gerber)
  8911. except PermissionError:
  8912. self.inform.emit('[WARNING] %s' %
  8913. _("Permission denied, saving not possible.\n"
  8914. "Most likely another app is holding the file open and not accessible."))
  8915. return 'fail'
  8916. if self.defaults["global_open_style"] is False:
  8917. self.file_opened.emit("Gerber", filename)
  8918. self.file_saved.emit("Gerber", filename)
  8919. self.inform.emit('[success] %s: %s' %
  8920. (_("Gerber file exported to"), filename))
  8921. else:
  8922. return exported_gerber
  8923. except Exception as e:
  8924. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8925. return 'fail'
  8926. if use_thread is True:
  8927. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8928. def job_thread_grb(app_obj):
  8929. ret = make_gerber()
  8930. if ret == 'fail':
  8931. self.inform.emit('[ERROR_NOTCL] %s' %
  8932. _('Could not export Gerber file.'))
  8933. return
  8934. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8935. else:
  8936. ret = make_gerber()
  8937. if ret == 'fail':
  8938. self.inform.emit('[ERROR_NOTCL] %s' %
  8939. _('Could not export Gerber file.'))
  8940. return 'fail'
  8941. if local_use is not None:
  8942. return ret
  8943. def export_dxf(self, obj_name, filename, use_thread=True):
  8944. """
  8945. Exports a Geometry Object to an DXF file.
  8946. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8947. :param filename: Path to the DXF file to save to.
  8948. :param use_thread: if to be run in a separate thread
  8949. :return:
  8950. """
  8951. self.report_usage("export_dxf()")
  8952. if filename is None:
  8953. filename = self.defaults["global_last_save_folder"]
  8954. self.log.debug("export_dxf()")
  8955. try:
  8956. obj = self.collection.get_by_name(str(obj_name))
  8957. except Exception:
  8958. # TODO: The return behavior has not been established... should raise exception?
  8959. return "Could not retrieve object: %s" % obj_name
  8960. def make_dxf():
  8961. try:
  8962. dxf_code = obj.export_dxf()
  8963. dxf_code.saveas(filename)
  8964. if self.defaults["global_open_style"] is False:
  8965. self.file_opened.emit("DXF", filename)
  8966. self.file_saved.emit("DXF", filename)
  8967. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  8968. except Exception:
  8969. return 'fail'
  8970. if use_thread is True:
  8971. with self.proc_container.new(_("Exporting DXF")) as proc:
  8972. def job_thread_exc(app_obj):
  8973. ret_dxf_val = make_dxf()
  8974. if ret_dxf_val == 'fail':
  8975. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8976. return
  8977. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8978. else:
  8979. ret = make_dxf()
  8980. if ret == 'fail':
  8981. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  8982. return
  8983. def import_svg(self, filename, geo_type='geometry', outname=None):
  8984. """
  8985. Adds a new Geometry Object to the projects and populates
  8986. it with shapes extracted from the SVG file.
  8987. :param filename: Path to the SVG file.
  8988. :param geo_type: Type of FlatCAM object that will be created from SVG
  8989. :param outname:
  8990. :return:
  8991. """
  8992. self.report_usage("import_svg()")
  8993. log.debug("App.import_svg()")
  8994. obj_type = ""
  8995. if geo_type is None or geo_type == "geometry":
  8996. obj_type = "geometry"
  8997. elif geo_type == "gerber":
  8998. obj_type = "gerber"
  8999. else:
  9000. self.inform.emit('[ERROR_NOTCL] %s' %
  9001. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  9002. return
  9003. units = self.defaults['units'].upper()
  9004. def obj_init(geo_obj, app_obj):
  9005. geo_obj.import_svg(filename, obj_type, units=units)
  9006. geo_obj.multigeo = False
  9007. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  9008. with self.proc_container.new(_("Importing SVG")) as proc:
  9009. # Object name
  9010. name = outname or filename.split('/')[-1].split('\\')[-1]
  9011. self.new_object(obj_type, name, obj_init, autoselected=False)
  9012. # Register recent file
  9013. self.file_opened.emit("svg", filename)
  9014. # GUI feedback
  9015. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9016. def import_dxf(self, filename, geo_type='geometry', outname=None):
  9017. """
  9018. Adds a new Geometry Object to the projects and populates
  9019. it with shapes extracted from the DXF file.
  9020. :param filename: Path to the DXF file.
  9021. :param geo_type: Type of FlatCAM object that will be created from DXF
  9022. :param outname:
  9023. :type putname: str
  9024. :return:
  9025. """
  9026. self.report_usage("import_dxf()")
  9027. obj_type = ""
  9028. if geo_type is None or geo_type == "geometry":
  9029. obj_type = "geometry"
  9030. elif geo_type == "gerber":
  9031. obj_type = geo_type
  9032. else:
  9033. self.inform.emit('[ERROR_NOTCL] %s' %
  9034. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  9035. return
  9036. units = self.defaults['units'].upper()
  9037. def obj_init(geo_obj, app_obj):
  9038. geo_obj.import_dxf(filename, obj_type, units=units)
  9039. geo_obj.multigeo = False
  9040. with self.proc_container.new(_("Importing DXF")) as proc:
  9041. # Object name
  9042. name = outname or filename.split('/')[-1].split('\\')[-1]
  9043. self.new_object(obj_type, name, obj_init, autoselected=False)
  9044. self.progress.emit(20)
  9045. # Register recent file
  9046. self.file_opened.emit("dxf", filename)
  9047. # GUI feedback
  9048. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9049. self.progress.emit(100)
  9050. def open_gerber(self, filename, outname=None):
  9051. """
  9052. Opens a Gerber file, parses it and creates a new object for
  9053. it in the program. Thread-safe.
  9054. :param outname: Name of the resulting object. None causes the
  9055. name to be that of the file.
  9056. :param filename: Gerber file filename
  9057. :type filename: str
  9058. :return: None
  9059. """
  9060. # How the object should be initialized
  9061. def obj_init(gerber_obj, app_obj):
  9062. assert isinstance(gerber_obj, FlatCAMGerber), \
  9063. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  9064. # Opening the file happens here
  9065. try:
  9066. gerber_obj.parse_file(filename)
  9067. except IOError:
  9068. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  9069. return "fail"
  9070. except ParseError as err:
  9071. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  9072. app_obj.log.error(str(err))
  9073. return "fail"
  9074. except Exception as e:
  9075. log.debug("App.open_gerber() --> %s" % str(e))
  9076. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  9077. msg += traceback.format_exc()
  9078. app_obj.inform.emit(msg)
  9079. return "fail"
  9080. if gerber_obj.is_empty():
  9081. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  9082. _("Object is not Gerber file or empty. Aborting object creation."))
  9083. return "fail"
  9084. App.log.debug("open_gerber()")
  9085. with self.proc_container.new(_("Opening Gerber")) as proc:
  9086. # Object name
  9087. name = outname or filename.split('/')[-1].split('\\')[-1]
  9088. # # ## Object creation # ##
  9089. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  9090. if ret == 'fail':
  9091. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open Gerber failed. Probable not a Gerber file.'))
  9092. return 'fail'
  9093. # Register recent file
  9094. self.file_opened.emit("gerber", filename)
  9095. # GUI feedback
  9096. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9097. def open_excellon(self, filename, outname=None, plot=True):
  9098. """
  9099. Opens an Excellon file, parses it and creates a new object for
  9100. it in the program. Thread-safe.
  9101. :param outname: Name of the resulting object. None causes the
  9102. name to be that of the file.
  9103. :param filename: Excellon file filename
  9104. :type filename: str
  9105. :return: None
  9106. """
  9107. App.log.debug("open_excellon()")
  9108. # How the object should be initialized
  9109. def obj_init(excellon_obj, app_obj):
  9110. # self.progress.emit(20)
  9111. try:
  9112. ret = excellon_obj.parse_file(filename=filename)
  9113. if ret == "fail":
  9114. log.debug("Excellon parsing failed.")
  9115. self.inform.emit('[ERROR_NOTCL] %s' %
  9116. _("This is not Excellon file."))
  9117. return "fail"
  9118. except IOError:
  9119. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  9120. (_("Cannot open file"), filename))
  9121. log.debug("Could not open Excellon object.")
  9122. self.progress.emit(0) # TODO: self and app_bjj mixed
  9123. return "fail"
  9124. except Exception:
  9125. msg = '[ERROR_NOTCL] %s' % \
  9126. _("An internal error has occurred. See shell.\n")
  9127. msg += traceback.format_exc()
  9128. app_obj.inform.emit(msg)
  9129. return "fail"
  9130. ret = excellon_obj.create_geometry()
  9131. if ret == 'fail':
  9132. log.debug("Could not create geometry for Excellon object.")
  9133. return "fail"
  9134. for tool in excellon_obj.tools:
  9135. if excellon_obj.tools[tool]['solid_geometry']:
  9136. return
  9137. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  9138. (_("No geometry found in file"), filename))
  9139. return "fail"
  9140. with self.proc_container.new(_("Opening Excellon.")):
  9141. # Object name
  9142. name = outname or filename.split('/')[-1].split('\\')[-1]
  9143. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  9144. if ret_val == 'fail':
  9145. self.inform.emit('[ERROR_NOTCL] %s' %
  9146. _('Open Excellon file failed. Probable not an Excellon file.'))
  9147. return
  9148. # Register recent file
  9149. self.file_opened.emit("excellon", filename)
  9150. # GUI feedback
  9151. self.inform.emit('[success] %s: %s' %
  9152. (_("Opened"), filename))
  9153. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True):
  9154. """
  9155. Opens a G-gcode file, parses it and creates a new object for
  9156. it in the program. Thread-safe.
  9157. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9158. :param filename: G-code file filename
  9159. :type filename: str
  9160. :return: None
  9161. """
  9162. App.log.debug("open_gcode()")
  9163. # How the object should be initialized
  9164. def obj_init(job_obj, app_obj_):
  9165. """
  9166. :param job_obj: the resulting object
  9167. :type app_obj_: App
  9168. """
  9169. assert isinstance(app_obj_, App), \
  9170. "Initializer expected App, got %s" % type(app_obj_)
  9171. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  9172. try:
  9173. f = open(filename)
  9174. gcode = f.read()
  9175. f.close()
  9176. except IOError:
  9177. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  9178. (_("Failed to open"), filename))
  9179. return "fail"
  9180. job_obj.gcode = gcode
  9181. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  9182. if gcode_ret == "fail":
  9183. self.inform.emit('[ERROR_NOTCL] %s' %
  9184. _("This is not GCODE"))
  9185. return "fail"
  9186. job_obj.create_geometry()
  9187. with self.proc_container.new(_("Opening G-Code.")):
  9188. # Object name
  9189. name = outname or filename.split('/')[-1].split('\\')[-1]
  9190. # New object creation and file processing
  9191. obj_ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  9192. if obj_ret == 'fail':
  9193. self.inform.emit('[ERROR_NOTCL] %s' %
  9194. _("Failed to create CNCJob Object. Probable not a GCode file. "
  9195. "Try to load it from File menu.\n "
  9196. "Attempting to create a FlatCAM CNCJob Object from "
  9197. "G-Code file failed during processing"))
  9198. return "fail"
  9199. # Register recent file
  9200. self.file_opened.emit("cncjob", filename)
  9201. # GUI feedback
  9202. self.inform.emit('[success] %s: %s' %
  9203. (_("Opened"), filename))
  9204. def open_hpgl2(self, filename, outname=None):
  9205. """
  9206. Opens a HPGL2 file, parses it and creates a new object for
  9207. it in the program. Thread-safe.
  9208. :param outname: Name of the resulting object. None causes the
  9209. name to be that of the file.
  9210. :param filename: HPGL2 file filename
  9211. :type filename: str
  9212. :return: None
  9213. """
  9214. filename = filename
  9215. # How the object should be initialized
  9216. def obj_init(geo_obj, app_obj):
  9217. assert isinstance(geo_obj, FlatCAMGeometry), \
  9218. "Expected to initialize a FlatCAMGeometry but got %s" % type(geo_obj)
  9219. # Opening the file happens here
  9220. obj = HPGL2(self)
  9221. try:
  9222. HPGL2.parse_file(obj, filename)
  9223. except IOError:
  9224. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  9225. return "fail"
  9226. except ParseError as err:
  9227. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  9228. app_obj.log.error(str(err))
  9229. return "fail"
  9230. except Exception as e:
  9231. log.debug("App.open_hpgl2() --> %s" % str(e))
  9232. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  9233. msg += traceback.format_exc()
  9234. app_obj.inform.emit(msg)
  9235. return "fail"
  9236. geo_obj.multigeo = True
  9237. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  9238. geo_obj.tools = deepcopy(obj.tools)
  9239. geo_obj.source_file = deepcopy(obj.source_file)
  9240. del obj
  9241. if not geo_obj.solid_geometry:
  9242. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  9243. _("Object is not HPGL2 file or empty. Aborting object creation."))
  9244. return "fail"
  9245. App.log.debug("open_hpgl2()")
  9246. with self.proc_container.new(_("Opening HPGL2")) as proc:
  9247. # Object name
  9248. name = outname or filename.split('/')[-1].split('\\')[-1]
  9249. # # ## Object creation # ##
  9250. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  9251. if ret == 'fail':
  9252. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  9253. return 'fail'
  9254. # Register recent file
  9255. self.file_opened.emit("geometry", filename)
  9256. # GUI feedback
  9257. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9258. def open_script(self, filename, outname=None, silent=False):
  9259. """
  9260. Opens a Script file, parses it and creates a new object for
  9261. it in the program. Thread-safe.
  9262. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9263. :param filename: Script file filename
  9264. :type filename: str
  9265. :return: None
  9266. """
  9267. App.log.debug("open_script()")
  9268. with self.proc_container.new(_("Opening TCL Script...")):
  9269. try:
  9270. with open(filename, "r") as opened_script:
  9271. script_content = opened_script.readlines()
  9272. script_content = ''.join(script_content)
  9273. if silent is False:
  9274. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  9275. except Exception as e:
  9276. log.debug("App.open_script() -> %s" % str(e))
  9277. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  9278. return
  9279. # Object name
  9280. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  9281. # New object creation and file processing
  9282. self.on_filenewscript(name=script_name, text=script_content)
  9283. # Register recent file
  9284. self.file_opened.emit("script", filename)
  9285. # GUI feedback
  9286. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9287. def open_config_file(self, filename, run_from_arg=None):
  9288. """
  9289. Loads a config file from the specified file.
  9290. :param filename: Name of the file from which to load.
  9291. :type filename: str
  9292. :return: None
  9293. """
  9294. App.log.debug("Opening config file: " + filename)
  9295. if run_from_arg:
  9296. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9297. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9298. _("Opening FlatCAM Config file.")),
  9299. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9300. color=QtGui.QColor("gray"))
  9301. # # add the tab if it was closed
  9302. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  9303. # # first clear previous text in text editor (if any)
  9304. # self.ui.text_editor_tab.code_editor.clear()
  9305. #
  9306. # # Switch plot_area to CNCJob tab
  9307. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  9308. # close the Code editor if already open
  9309. if self.toggle_codeeditor:
  9310. self.on_toggle_code_editor()
  9311. self.on_toggle_code_editor()
  9312. try:
  9313. if filename:
  9314. f = QtCore.QFile(filename)
  9315. if f.open(QtCore.QIODevice.ReadOnly):
  9316. stream = QtCore.QTextStream(f)
  9317. code_edited = stream.readAll()
  9318. self.text_editor_tab.code_editor.setPlainText(code_edited)
  9319. f.close()
  9320. except IOError:
  9321. App.log.error("Failed to open config file: %s" % filename)
  9322. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9323. (_("Failed to open config file"), filename))
  9324. return
  9325. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  9326. """
  9327. Loads a project from the specified file.
  9328. 1) Loads and parses file
  9329. 2) Registers the file as recently opened.
  9330. 3) Calls on_file_new()
  9331. 4) Updates options
  9332. 5) Calls new_object() with the object's from_dict() as init method.
  9333. 6) Calls plot_all() if plot=True
  9334. :param filename: Name of the file from which to load.
  9335. :type filename: str
  9336. :param run_from_arg: True if run for arguments
  9337. :param plot: If True plot all objects in the project
  9338. :param cli: run from command line
  9339. :return: None
  9340. """
  9341. App.log.debug("Opening project: " + filename)
  9342. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9343. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9344. if cli is None:
  9345. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  9346. if run_from_arg:
  9347. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9348. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9349. _("Opening FlatCAM Project file.")),
  9350. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9351. color=QtGui.QColor("gray"))
  9352. # Open and parse an uncompressed Project file
  9353. try:
  9354. f = open(filename, 'r')
  9355. except IOError:
  9356. App.log.error("Failed to open project file: %s" % filename)
  9357. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9358. (_("Failed to open project file"), filename))
  9359. return
  9360. try:
  9361. d = json.load(f, object_hook=dict2obj)
  9362. except Exception as e:
  9363. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  9364. (filename, str(e)))
  9365. f.close()
  9366. # Open and parse a compressed Project file
  9367. try:
  9368. with lzma.open(filename) as f:
  9369. file_content = f.read().decode('utf-8')
  9370. d = json.loads(file_content, object_hook=dict2obj)
  9371. except Exception as e:
  9372. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  9373. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9374. (_("Failed to open project file"), filename))
  9375. return
  9376. # Clear the current project
  9377. # # NOT THREAD SAFE # ##
  9378. if run_from_arg is True:
  9379. pass
  9380. elif cli is True:
  9381. self.delete_selection_shape()
  9382. else:
  9383. self.on_file_new()
  9384. # Project options
  9385. self.options.update(d['options'])
  9386. self.project_filename = filename
  9387. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9388. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9389. if cli is None:
  9390. self.set_screen_units(self.options["units"])
  9391. # Re create objects
  9392. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  9393. for obj in d['objs']:
  9394. def obj_init(obj_inst, app_inst):
  9395. obj_inst.from_dict(obj)
  9396. App.log.debug("Recreating from opened project an %s object: %s" %
  9397. (obj['kind'].capitalize(), obj['options']['name']))
  9398. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9399. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9400. if cli is None:
  9401. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  9402. obj['kind'].upper(),
  9403. obj['options']['name']
  9404. )
  9405. )
  9406. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  9407. self.inform.emit('[success] %s: %s' %
  9408. (_("Project loaded from"), filename))
  9409. self.should_we_save = False
  9410. self.file_opened.emit("project", filename)
  9411. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9412. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9413. if cli is None:
  9414. self.set_ui_title(name=self.project_filename)
  9415. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  9416. def propagate_defaults(self, silent=False):
  9417. """
  9418. This method is used to set default values in classes. It's
  9419. an alternative to project options but allows the use
  9420. of values invisible to the user.
  9421. :return: None
  9422. """
  9423. if silent is False:
  9424. self.log.debug("propagate_defaults()")
  9425. # Which objects to update the given parameters.
  9426. routes = {
  9427. "global_zdownrate": CNCjob,
  9428. "excellon_zeros": Excellon,
  9429. "excellon_format_upper_in": Excellon,
  9430. "excellon_format_lower_in": Excellon,
  9431. "excellon_format_upper_mm": Excellon,
  9432. "excellon_format_lower_mm": Excellon,
  9433. "excellon_units": Excellon,
  9434. "gerber_use_buffer_for_union": Gerber,
  9435. "geometry_multidepth": Geometry
  9436. }
  9437. for param in routes:
  9438. if param in routes[param].defaults:
  9439. try:
  9440. routes[param].defaults[param] = self.defaults[param]
  9441. if silent is False:
  9442. self.log.debug(" " + param + " OK")
  9443. except KeyError:
  9444. if silent is False:
  9445. self.log.debug("FlatCAMApp.propagate_defaults() --> ERROR: " + param + " not in defaults.")
  9446. else:
  9447. # Try extracting the name:
  9448. # classname_param here is param in the object
  9449. if param.find(routes[param].__name__.lower() + "_") == 0:
  9450. p = param[len(routes[param].__name__) + 1:]
  9451. if p in routes[param].defaults:
  9452. routes[param].defaults[p] = self.defaults[param]
  9453. if silent is False:
  9454. self.log.debug(" " + param + " OK!")
  9455. def plot_all(self, zoom=True):
  9456. """
  9457. Re-generates all plots from all objects.
  9458. :return: None
  9459. """
  9460. self.log.debug("Plot_all()")
  9461. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  9462. for obj in self.collection.get_list():
  9463. def worker_task(obj):
  9464. with self.proc_container.new("Plotting"):
  9465. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  9466. if zoom:
  9467. self.object_plotted.emit(obj)
  9468. # Send to worker
  9469. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  9470. def register_folder(self, filename):
  9471. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  9472. def register_save_folder(self, filename):
  9473. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  9474. def set_progress_bar(self, percentage, text=""):
  9475. self.ui.progress_bar.setValue(int(percentage))
  9476. def setup_shell(self):
  9477. """
  9478. Creates shell functions. Runs once at startup.
  9479. :return: None
  9480. """
  9481. self.log.debug("setup_shell()")
  9482. def shelp(p=None):
  9483. if not p:
  9484. return _("Available commands:\n") + \
  9485. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  9486. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  9487. if p not in commands:
  9488. return "Unknown command: %s" % p
  9489. return commands[p]["help"]
  9490. # --- Migrated to new architecture ---
  9491. # def options(name):
  9492. # ops = self.collection.get_by_name(str(name)).options
  9493. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  9494. def h(*args):
  9495. """
  9496. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  9497. and standalone parameters into list.
  9498. """
  9499. kwa = {}
  9500. a = []
  9501. n = len(args)
  9502. name = None
  9503. for i in range(n):
  9504. match = re.search(r'^-([a-zA-Z].*)', args[i])
  9505. if match:
  9506. assert name is None
  9507. name = match.group(1)
  9508. continue
  9509. if name is None:
  9510. a.append(args[i])
  9511. else:
  9512. kwa[name] = args[i]
  9513. name = None
  9514. return a, kwa
  9515. @contextmanager
  9516. def wait_signal(signal, timeout=10000):
  9517. """
  9518. Block loop until signal emitted, timeout (ms) elapses
  9519. or unhandled exception happens in a thread.
  9520. :param timeout: time after which the loop is exited
  9521. :param signal: Signal to wait for.
  9522. """
  9523. loop = QtCore.QEventLoop()
  9524. # Normal termination
  9525. signal.connect(loop.quit)
  9526. # Termination by exception in thread
  9527. self.thread_exception.connect(loop.quit)
  9528. status = {'timed_out': False}
  9529. def report_quit():
  9530. status['timed_out'] = True
  9531. loop.quit()
  9532. yield
  9533. # Temporarily change how exceptions are managed.
  9534. oeh = sys.excepthook
  9535. ex = []
  9536. def except_hook(type_, value, traceback_):
  9537. ex.append(value)
  9538. oeh(type_, value, traceback_)
  9539. sys.excepthook = except_hook
  9540. # Terminate on timeout
  9541. if timeout is not None:
  9542. QtCore.QTimer.singleShot(timeout, report_quit)
  9543. # # ## Block ## ##
  9544. loop.exec_()
  9545. # Restore exception management
  9546. sys.excepthook = oeh
  9547. if ex:
  9548. self.raiseTclError(str(ex[0]))
  9549. if status['timed_out']:
  9550. raise Exception('Timed out!')
  9551. def make_docs():
  9552. output = ''
  9553. import collections
  9554. od = collections.OrderedDict(sorted(commands.items()))
  9555. for cmd_, val in od.items():
  9556. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  9557. t = val['help']
  9558. usage_i = t.find('>')
  9559. if usage_i < 0:
  9560. expl = t
  9561. output += expl + '\n\n'
  9562. continue
  9563. expl = t[:usage_i - 1]
  9564. output += expl + '\n\n'
  9565. end_usage_i = t[usage_i:].find('\n')
  9566. if end_usage_i < 0:
  9567. end_usage_i = len(t[usage_i:])
  9568. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  9569. else:
  9570. extras = t[usage_i+end_usage_i+1:]
  9571. parts = [s.strip() for s in extras.split('\n')]
  9572. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  9573. for p in parts:
  9574. output += ' ' + p + '\n\n'
  9575. return output
  9576. '''
  9577. Howto implement TCL shell commands:
  9578. All parameters passed to command should be possible to set as None and test it afterwards.
  9579. This is because we need to see error caused in tcl,
  9580. if None value as default parameter is not allowed TCL will return empty error.
  9581. Use:
  9582. def mycommand(name=None,...):
  9583. Test it like this:
  9584. if name is None:
  9585. self.raise_tcl_error('Argument name is missing.')
  9586. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  9587. otherwise we will miss it and processing will silently continue.
  9588. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  9589. which is catched in exec_command and displayed in TCL shell console with red background.
  9590. Error in console is displayed with TCL trace.
  9591. This behavior works only within main thread,
  9592. errors with promissed tasks can be catched and detected only with log.
  9593. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  9594. TCL shell.
  9595. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  9596. '''
  9597. commands = {
  9598. 'help': {
  9599. 'fcn': shelp,
  9600. 'help': _("Shows list of commands.")
  9601. },
  9602. }
  9603. # Import/overwrite tcl commands as objects of TclCommand descendants
  9604. # This modifies the variable 'commands'.
  9605. tclCommands.register_all_commands(self, commands)
  9606. # Add commands to the tcl interpreter
  9607. for cmd in commands:
  9608. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  9609. # Make the tcl puts function return instead of print to stdout
  9610. self.tcl.eval('''
  9611. rename puts original_puts
  9612. proc puts {args} {
  9613. if {[llength $args] == 1} {
  9614. return "[lindex $args 0]"
  9615. } else {
  9616. eval original_puts $args
  9617. }
  9618. }
  9619. ''')
  9620. def setup_recent_items(self):
  9621. # TODO: Move this to constructor
  9622. icons = {
  9623. "gerber": self.resource_location + "/flatcam_icon16.png",
  9624. "excellon": self.resource_location + "/drill16.png",
  9625. 'geometry': self.resource_location + "/geometry16.png",
  9626. "cncjob": self.resource_location + "/cnc16.png",
  9627. "script": self.resource_location + "/script_new24.png",
  9628. "document": self.resource_location + "/notes16_1.png",
  9629. "project": self.resource_location + "/project16.png",
  9630. "svg": self.resource_location + "/geometry16.png",
  9631. "dxf": self.resource_location + "/dxf16.png",
  9632. "pdf": self.resource_location + "/pdf32.png",
  9633. "image": self.resource_location + "/image16.png"
  9634. }
  9635. openers = {
  9636. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  9637. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  9638. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  9639. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  9640. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  9641. "document": None,
  9642. 'project': self.open_project,
  9643. 'svg': self.import_svg,
  9644. 'dxf': self.import_dxf,
  9645. 'image': self.image_tool.import_image,
  9646. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  9647. }
  9648. # Open recent file for files
  9649. try:
  9650. f = open(self.data_path + '/recent.json')
  9651. except IOError:
  9652. App.log.error("Failed to load recent item list.")
  9653. self.inform.emit('[ERROR_NOTCL] %s' %
  9654. _("Failed to load recent item list."))
  9655. return
  9656. try:
  9657. self.recent = json.load(f)
  9658. except json.scanner.JSONDecodeError:
  9659. App.log.error("Failed to parse recent item list.")
  9660. self.inform.emit('[ERROR_NOTCL] %s' %
  9661. _("Failed to parse recent item list."))
  9662. f.close()
  9663. return
  9664. f.close()
  9665. # Open recent file for projects
  9666. try:
  9667. fp = open(self.data_path + '/recent_projects.json')
  9668. except IOError:
  9669. App.log.error("Failed to load recent project item list.")
  9670. self.inform.emit('[ERROR_NOTCL] %s' %
  9671. _("Failed to load recent projects item list."))
  9672. return
  9673. try:
  9674. self.recent_projects = json.load(fp)
  9675. except json.scanner.JSONDecodeError:
  9676. App.log.error("Failed to parse recent project item list.")
  9677. self.inform.emit('[ERROR_NOTCL] %s' %
  9678. _("Failed to parse recent project item list."))
  9679. fp.close()
  9680. return
  9681. fp.close()
  9682. # Closure needed to create callbacks in a loop.
  9683. # Otherwise late binding occurs.
  9684. def make_callback(func, fname):
  9685. def opener():
  9686. func(fname)
  9687. return opener
  9688. def reset_recent_files():
  9689. # Reset menu
  9690. self.ui.recent.clear()
  9691. self.recent = []
  9692. try:
  9693. ff = open(self.data_path + '/recent.json', 'w')
  9694. except IOError:
  9695. App.log.error("Failed to open recent items file for writing.")
  9696. return
  9697. json.dump(self.recent, ff)
  9698. def reset_recent_projects():
  9699. # Reset menu
  9700. self.ui.recent_projects.clear()
  9701. self.recent_projects = []
  9702. try:
  9703. fp = open(self.data_path + '/recent_projects.json', 'w')
  9704. except IOError:
  9705. App.log.error("Failed to open recent projects items file for writing.")
  9706. return
  9707. json.dump(self.recent, fp)
  9708. # Reset menu
  9709. self.ui.recent.clear()
  9710. self.ui.recent_projects.clear()
  9711. # Create menu items for projects
  9712. for recent in self.recent_projects:
  9713. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9714. if recent['kind'] == 'project':
  9715. try:
  9716. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9717. # Attach callback
  9718. o = make_callback(openers[recent["kind"]], recent['filename'])
  9719. action.triggered.connect(o)
  9720. self.ui.recent_projects.addAction(action)
  9721. except KeyError:
  9722. App.log.error("Unsupported file type: %s" % recent["kind"])
  9723. # Last action in Recent Files menu is one that Clear the content
  9724. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  9725. (_("Clear Recent projects")), self)
  9726. clear_action_proj.triggered.connect(reset_recent_projects)
  9727. self.ui.recent_projects.addSeparator()
  9728. self.ui.recent_projects.addAction(clear_action_proj)
  9729. # Create menu items for files
  9730. for recent in self.recent:
  9731. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  9732. if recent['kind'] != 'project':
  9733. try:
  9734. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  9735. # Attach callback
  9736. o = make_callback(openers[recent["kind"]], recent['filename'])
  9737. action.triggered.connect(o)
  9738. self.ui.recent.addAction(action)
  9739. except KeyError:
  9740. App.log.error("Unsupported file type: %s" % recent["kind"])
  9741. # Last action in Recent Files menu is one that Clear the content
  9742. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  9743. (_("Clear Recent files")), self)
  9744. clear_action.triggered.connect(reset_recent_files)
  9745. self.ui.recent.addSeparator()
  9746. self.ui.recent.addAction(clear_action)
  9747. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  9748. # self.ui.menufilerecent.set_submenu(recent_menu)
  9749. # recent_menu.show_all()
  9750. # self.ui.recent.show()
  9751. self.log.debug("Recent items list has been populated.")
  9752. def setup_component_editor(self):
  9753. # label = QtWidgets.QLabel("Choose an item from Project")
  9754. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  9755. sel_title = QtWidgets.QTextEdit(
  9756. _('<b>Shortcut Key List</b>'))
  9757. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  9758. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  9759. settings = QSettings("Open Source", "FlatCAM")
  9760. if settings.contains("notebook_font_size"):
  9761. fsize = settings.value('notebook_font_size', type=int)
  9762. else:
  9763. fsize = 12
  9764. tsize = fsize + int(fsize / 2)
  9765. # selected_text = (_('''
  9766. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  9767. #
  9768. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  9769. # The normal flow when working in FlatCAM is the following:</span></p>
  9770. #
  9771. # <ol>
  9772. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  9773. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  9774. # even dragging and dropping the files on the GUI.<br />
  9775. # <br />
  9776. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  9777. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9778. # &nbsp;</li>
  9779. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  9780. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9781. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9782. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9783. # <br />
  9784. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  9785. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9786. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9787. # it even if it was out of focus.<br />
  9788. # <br />
  9789. # You can change the parameters in this screen and the flow direction is like this:<br />
  9790. # <br />
  9791. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  9792. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9793. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9794. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9795. # </ol>
  9796. #
  9797. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9798. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9799. # <strong>F3</strong>.</span></p>
  9800. #
  9801. # ''').format(fsize=fsize, tsize=tsize))
  9802. selected_text = '''
  9803. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  9804. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  9805. {s1}</span></p>
  9806. <ol>
  9807. <li><span style="font-size:{fsize}px">{s2}<br />
  9808. <br />
  9809. {s3}</span><br />
  9810. &nbsp;</li>
  9811. <li><span style="font-size:{fsize}px">{s4}<br />
  9812. &nbsp;</li>
  9813. <br />
  9814. <li><span style="font-size:{fsize}px">{s5}<br />
  9815. &nbsp;</li>
  9816. <br />
  9817. <li><span style="font-size:{fsize}px">{s6}<br />
  9818. <br />
  9819. {s7}</span></li>
  9820. </ol>
  9821. <p><span style="font-size:{fsize}px">{s8}</span></p>
  9822. '''.format(
  9823. title=_("Selected Tab - Choose an Item from Project Tab"),
  9824. subtitle=_("Details"),
  9825. s1=_("The normal flow when working in FlatCAM is the following:"),
  9826. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  9827. "using either the toolbars, key shortcuts or even dragging and dropping the "
  9828. "files on the GUI."),
  9829. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  9830. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  9831. "actions offered within the app."),
  9832. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  9833. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  9834. "SELECTED TAB will be updated with the object properties according to its kind: "
  9835. "Gerber, Excellon, Geometry or CNCJob object."),
  9836. s5=_("If the selection of the object is done on the canvas by single click instead, "
  9837. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  9838. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  9839. "the SELECTED TAB and populate it even if it was out of focus."),
  9840. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  9841. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  9842. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  9843. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  9844. "(again, done in SELECTED TAB) --> Save GCode."),
  9845. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  9846. "or through its own key shortcut: <b>F3</b>."),
  9847. tsize=tsize,
  9848. fsize=fsize
  9849. )
  9850. sel_title.setText(selected_text)
  9851. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9852. self.ui.selected_scroll_area.setWidget(sel_title)
  9853. def setup_obj_classes(self):
  9854. """
  9855. Sets up application specifics on the FlatCAMObj class.
  9856. :return: None
  9857. """
  9858. FlatCAMObj.app = self
  9859. ObjectCollection.app = self
  9860. Gerber.app = self
  9861. Excellon.app = self
  9862. Geometry.app = self
  9863. CNCjob.app = self
  9864. FCProcess.app = self
  9865. FCProcessContainer.app = self
  9866. def version_check(self):
  9867. """
  9868. Checks for the latest version of the program. Alerts the
  9869. user if theirs is outdated. This method is meant to be run
  9870. in a separate thread.
  9871. :return: None
  9872. """
  9873. self.log.debug("version_check()")
  9874. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9875. full_url = App.version_url + \
  9876. "?s=" + str(self.defaults['global_serial']) + \
  9877. "&v=" + str(self.version) + \
  9878. "&os=" + str(self.os) + \
  9879. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  9880. else:
  9881. # no_stats dict; just so it won't break things on website
  9882. no_ststs_dict = {}
  9883. no_ststs_dict["global_ststs"] = {}
  9884. full_url = App.version_url + \
  9885. "?s=" + str(self.defaults['global_serial']) + \
  9886. "&v=" + str(self.version) + \
  9887. "&os=" + str(self.os) + \
  9888. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9889. App.log.debug("Checking for updates @ %s" % full_url)
  9890. # ## Get the data
  9891. try:
  9892. f = urllib.request.urlopen(full_url)
  9893. except Exception:
  9894. # App.log.warning("Failed checking for latest version. Could not connect.")
  9895. self.log.warning("Failed checking for latest version. Could not connect.")
  9896. self.inform.emit('[WARNING_NOTCL] %s' %
  9897. _("Failed checking for latest version. Could not connect."))
  9898. return
  9899. try:
  9900. data = json.load(f)
  9901. except Exception as e:
  9902. App.log.error("Could not parse information about latest version.")
  9903. self.inform.emit('[ERROR_NOTCL] %s' %
  9904. _("Could not parse information about latest version."))
  9905. App.log.debug("json.load(): %s" % str(e))
  9906. f.close()
  9907. return
  9908. f.close()
  9909. # ## Latest version?
  9910. if self.version >= data["version"]:
  9911. App.log.debug("FlatCAM is up to date!")
  9912. self.inform.emit('[success] %s' %
  9913. _("FlatCAM is up to date!"))
  9914. return
  9915. App.log.debug("Newer version available.")
  9916. self.message.emit(
  9917. _("Newer Version Available"),
  9918. _("There is a newer version of FlatCAM available for download:\n\n") +
  9919. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9920. _("info")
  9921. )
  9922. def on_plotcanvas_setup(self, container=None):
  9923. """
  9924. This is doing the setup for the plot area (VisPy canvas)
  9925. :param container: widget where to install the canvas
  9926. :return: None
  9927. """
  9928. if container:
  9929. plot_container = container
  9930. else:
  9931. plot_container = self.ui.right_layout
  9932. if self.is_legacy is False:
  9933. self.plotcanvas = PlotCanvas(plot_container, self)
  9934. else:
  9935. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9936. # So it can receive key presses
  9937. self.plotcanvas.native.setFocus()
  9938. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9939. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9940. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9941. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  9942. # Keys over plot enabled
  9943. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9944. if self.defaults['global_cursor_type'] == 'small':
  9945. self.app_cursor = self.plotcanvas.new_cursor()
  9946. else:
  9947. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  9948. if self.ui.grid_snap_btn.isChecked():
  9949. self.app_cursor.enabled = True
  9950. else:
  9951. self.app_cursor.enabled = False
  9952. if self.is_legacy is False:
  9953. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9954. else:
  9955. # will use the default Matplotlib axes
  9956. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  9957. def on_zoom_fit(self, event):
  9958. """
  9959. Callback for zoom-out request. This can be either from the corresponding
  9960. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9961. with axes limits from the geometry bounds of all objects.
  9962. :param event: Ignored.
  9963. :return: None
  9964. """
  9965. if self.is_legacy is False:
  9966. self.plotcanvas.fit_view()
  9967. else:
  9968. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  9969. width = xmax - xmin
  9970. height = ymax - ymin
  9971. xmin -= 0.05 * width
  9972. xmax += 0.05 * width
  9973. ymin -= 0.05 * height
  9974. ymax += 0.05 * height
  9975. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  9976. def on_zoom_in(self):
  9977. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9978. def on_zoom_out(self):
  9979. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9980. def disable_all_plots(self):
  9981. self.report_usage("disable_all_plots()")
  9982. self.disable_plots(self.collection.get_list())
  9983. self.inform.emit('[success] %s' %
  9984. _("All plots disabled."))
  9985. def disable_other_plots(self):
  9986. self.report_usage("disable_other_plots()")
  9987. self.disable_plots(self.collection.get_non_selected())
  9988. self.inform.emit('[success] %s' %
  9989. _("All non selected plots disabled."))
  9990. def enable_all_plots(self):
  9991. self.report_usage("enable_all_plots()")
  9992. self.enable_plots(self.collection.get_list())
  9993. self.inform.emit('[success] %s' %
  9994. _("All plots enabled."))
  9995. def on_enable_sel_plots(self):
  9996. log.debug("App.on_enable_sel_plot()")
  9997. object_list = self.collection.get_selected()
  9998. self.enable_plots(objects=object_list)
  9999. self.inform.emit('[success] %s' %
  10000. _("Selected plots enabled..."))
  10001. def on_disable_sel_plots(self):
  10002. log.debug("App.on_disable_sel_plot()")
  10003. # self.inform.emit(_("Disabling plots ..."))
  10004. object_list = self.collection.get_selected()
  10005. self.disable_plots(objects=object_list)
  10006. self.inform.emit('[success] %s' %
  10007. _("Selected plots disabled..."))
  10008. def enable_plots(self, objects):
  10009. """
  10010. Disables plots
  10011. :param objects: list of Objects to be enabled
  10012. :return:
  10013. """
  10014. log.debug("Enabling plots ...")
  10015. # self.inform.emit(_("Working ..."))
  10016. for obj in objects:
  10017. if obj.options['plot'] is False:
  10018. obj.options.set_change_callback(lambda x: None)
  10019. obj.options['plot'] = True
  10020. obj.options.set_change_callback(obj.on_options_change)
  10021. def worker_task(objs):
  10022. with self.proc_container.new(_("Enabling plots ...")):
  10023. for obj in objs:
  10024. # obj.options['plot'] = True
  10025. if isinstance(obj, FlatCAMCNCjob):
  10026. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  10027. else:
  10028. obj.plot(visible=True)
  10029. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  10030. # self.plots_updated.emit()
  10031. def disable_plots(self, objects):
  10032. """
  10033. Disables plots
  10034. :param objects: list of Objects to be disabled
  10035. :return:
  10036. """
  10037. # if no objects selected then do nothing
  10038. if not self.collection.get_selected():
  10039. return
  10040. log.debug("Disabling plots ...")
  10041. # self.inform.emit(_("Working ..."))
  10042. for obj in objects:
  10043. if obj.options['plot'] is True:
  10044. obj.options.set_change_callback(lambda x: None)
  10045. obj.options['plot'] = False
  10046. obj.options.set_change_callback(obj.on_options_change)
  10047. try:
  10048. self.delete_selection_shape()
  10049. except Exception as e:
  10050. log.debug("App.disable_plots() --> %s" % str(e))
  10051. # self.plots_updated.emit()
  10052. def worker_task(objs):
  10053. with self.proc_container.new(_("Disabling plots ...")):
  10054. for obj in objs:
  10055. # obj.options['plot'] = True
  10056. if isinstance(obj, FlatCAMCNCjob):
  10057. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  10058. else:
  10059. obj.plot(visible=False)
  10060. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  10061. def toggle_plots(self, objects):
  10062. """
  10063. Toggle plots visibility
  10064. :param objects: list of Objects for which to be toggled the visibility
  10065. :return:
  10066. """
  10067. # if no objects selected then do nothing
  10068. if not self.collection.get_selected():
  10069. return
  10070. log.debug("Toggling plots ...")
  10071. self.inform.emit(_("Working ..."))
  10072. for obj in objects:
  10073. if obj.options['plot'] is False:
  10074. obj.options['plot'] = True
  10075. else:
  10076. obj.options['plot'] = False
  10077. self.plots_updated.emit()
  10078. def clear_plots(self):
  10079. objects = self.collection.get_list()
  10080. for obj in objects:
  10081. obj.clear(obj == objects[-1])
  10082. # Clear pool to free memory
  10083. self.clear_pool()
  10084. def generate_cnc_job(self, objects):
  10085. self.report_usage("generate_cnc_job()")
  10086. # for obj in objects:
  10087. # obj.generatecncjob()
  10088. for obj in objects:
  10089. obj.on_generatecnc_button_click()
  10090. def save_project(self, filename, quit_action=False, silent=False):
  10091. """
  10092. Saves the current project to the specified file.
  10093. :param filename: Name of the file in which to save.
  10094. :type filename: str
  10095. :param quit_action: if the project saving will be followed by an app quit; boolean
  10096. :param silent: if True will not display status messages
  10097. :return: None
  10098. """
  10099. self.log.debug("save_project()")
  10100. self.save_in_progress = True
  10101. with self.proc_container.new(_("Saving FlatCAM Project")):
  10102. # Capture the latest changes
  10103. # Current object
  10104. try:
  10105. self.collection.get_active().read_form()
  10106. except Exception as e:
  10107. self.log.debug("There was no active object. %s" % str(e))
  10108. pass
  10109. # Serialize the whole project
  10110. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  10111. "options": self.options,
  10112. "version": self.version}
  10113. if self.defaults["global_save_compressed"] is True:
  10114. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  10115. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  10116. # # Write
  10117. f.write(g)
  10118. self.inform.emit('[success] %s: %s' %
  10119. (_("Project saved to"), filename))
  10120. else:
  10121. # Open file
  10122. try:
  10123. f = open(filename, 'w')
  10124. except IOError:
  10125. App.log.error("Failed to open file for saving: %s", filename)
  10126. return
  10127. # Write
  10128. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  10129. f.close()
  10130. # verification of the saved project
  10131. # Open and parse
  10132. try:
  10133. saved_f = open(filename, 'r')
  10134. except IOError:
  10135. if silent is False:
  10136. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  10137. (_("Failed to verify project file"), filename, _("Retry to save it."))
  10138. )
  10139. return
  10140. try:
  10141. saved_d = json.load(saved_f, object_hook=dict2obj)
  10142. except Exception:
  10143. if silent is False:
  10144. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  10145. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  10146. )
  10147. f.close()
  10148. return
  10149. saved_f.close()
  10150. if silent is False:
  10151. if 'version' in saved_d:
  10152. self.inform.emit('[success] %s: %s' %
  10153. (_("Project saved to"), filename))
  10154. else:
  10155. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  10156. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  10157. )
  10158. tb_settings = QSettings("Open Source", "FlatCAM")
  10159. lock_state = self.ui.lock_action.isChecked()
  10160. tb_settings.setValue('toolbar_lock', lock_state)
  10161. # This will write the setting to the platform specific storage.
  10162. del tb_settings
  10163. # if quit:
  10164. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  10165. # t.start()
  10166. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  10167. def start_delayed_quit(self, delay, filename, should_quit=None):
  10168. """
  10169. :param delay: period of checking if project file size is more than zero; in seconds
  10170. :param filename: the name of the project file to be checked periodically for size more than zero
  10171. :param should_quit: if the task finished will be followed by an app quit; boolean
  10172. :return:
  10173. """
  10174. to_quit = should_quit
  10175. self.save_timer = QtCore.QTimer()
  10176. self.save_timer.setInterval(delay)
  10177. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  10178. self.save_timer.start()
  10179. def check_project_file_size(self, filename, should_quit=None):
  10180. """
  10181. :param filename: the name of the project file to be checked periodically for size more than zero
  10182. :param should_quit: will quit the app if True; boolean
  10183. :return:
  10184. """
  10185. try:
  10186. if os.stat(filename).st_size > 0:
  10187. self.save_in_progress = False
  10188. self.save_timer.stop()
  10189. if should_quit:
  10190. self.app_quit.emit()
  10191. except Exception:
  10192. traceback.print_exc()
  10193. def on_plotarea_tab_closed(self, tab_idx):
  10194. widget = self.ui.plot_tab_area.widget(tab_idx)
  10195. if widget is not None:
  10196. widget.deleteLater()
  10197. self.ui.plot_tab_area.removeTab(tab_idx)
  10198. def on_options_app2project(self):
  10199. """
  10200. Callback for Options->Transfer Options->App=>Project. Copies options
  10201. from application defaults to project defaults.
  10202. :return: None
  10203. """
  10204. self.report_usage("on_options_app2project")
  10205. self.defaults_read_form()
  10206. self.options.update(self.defaults)
  10207. # self.options_write_form()
  10208. class ArgsThread(QtCore.QObject):
  10209. open_signal = pyqtSignal(list)
  10210. start = pyqtSignal()
  10211. if sys.platform == 'win32':
  10212. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  10213. else:
  10214. address = ('/tmp/testipc', 'AF_UNIX')
  10215. def __init__(self):
  10216. super(ArgsThread, self).__init__()
  10217. self.start.connect(self.run)
  10218. def my_loop(self, address):
  10219. try:
  10220. listener = Listener(*address)
  10221. while True:
  10222. conn = listener.accept()
  10223. self.serve(conn)
  10224. except socket.error:
  10225. conn = Client(*address)
  10226. conn.send(sys.argv)
  10227. conn.send('close')
  10228. # close the current instance only if there are args
  10229. if len(sys.argv) > 1:
  10230. sys.exit()
  10231. def serve(self, conn):
  10232. while True:
  10233. msg = conn.recv()
  10234. if msg == 'close':
  10235. break
  10236. self.open_signal.emit(msg)
  10237. conn.close()
  10238. # the decorator is a must; without it this technique will not work unless the start signal is connected
  10239. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  10240. @pyqtSlot()
  10241. def run(self):
  10242. self.my_loop(self.address)
  10243. class GracefulException(Exception):
  10244. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  10245. def __init__(self):
  10246. super().__init__()
  10247. def __str__(self):
  10248. return '\n\n%s' % _("The user requested a graceful exit of the current task.")
  10249. # end of file