FlatCAMApp.py 377 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578
  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, urllib.parse, urllib.error
  9. import getopt
  10. import random
  11. import simplejson as json
  12. import lzma
  13. import threading
  14. from stat import S_IREAD, S_IRGRP, S_IROTH
  15. import subprocess
  16. import tkinter as tk
  17. from PyQt5 import QtPrintSupport
  18. import urllib.request, urllib.parse, urllib.error
  19. from contextlib import contextmanager
  20. import gc
  21. from xml.dom.minidom import parseString as parse_xml_string
  22. ########################################
  23. ## Imports part of FlatCAM ##
  24. ########################################
  25. from ObjectCollection import *
  26. from FlatCAMObj import *
  27. from flatcamGUI.PlotCanvas import *
  28. from flatcamGUI.FlatCAMGUI import *
  29. from FlatCAMCommon import LoudDict
  30. from FlatCAMPostProc import load_postprocessors
  31. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  32. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  33. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  34. from FlatCAMProcess import *
  35. from FlatCAMWorkerStack import WorkerStack
  36. from flatcamGUI.VisPyVisuals import Color
  37. from vispy.gloo.util import _screenshot
  38. from vispy.io import write_png
  39. from flatcamTools import *
  40. from multiprocessing import Pool
  41. import tclCommands
  42. import gettext
  43. import FlatCAMTranslation as fcTranslate
  44. fcTranslate.apply_language('strings')
  45. import builtins
  46. if '_' not in builtins.__dict__:
  47. _ = gettext.gettext
  48. ########################################
  49. ## App ##
  50. ########################################
  51. class App(QtCore.QObject):
  52. """
  53. The main application class. The constructor starts the GUI.
  54. """
  55. # Get Cmd Line Options
  56. cmd_line_shellfile = ''
  57. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  58. try:
  59. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  60. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  61. except getopt.GetoptError:
  62. print(cmd_line_help)
  63. sys.exit(2)
  64. for opt, arg in cmd_line_options:
  65. if opt == '-h':
  66. print(cmd_line_help)
  67. sys.exit()
  68. elif opt == '--shellfile':
  69. cmd_line_shellfile = arg
  70. # Logging ##
  71. log = logging.getLogger('base')
  72. log.setLevel(logging.DEBUG)
  73. # log.setLevel(logging.WARNING)
  74. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  75. handler = logging.StreamHandler()
  76. handler.setFormatter(formatter)
  77. log.addHandler(handler)
  78. # Version
  79. version = 8.917
  80. version_date = "2019/05/18"
  81. beta = True
  82. # current date now
  83. date = str(datetime.today()).rpartition('.')[0]
  84. date = ''.join(c for c in date if c not in ':-')
  85. date = date.replace(' ', '_')
  86. # URL for update checks and statistics
  87. version_url = "http://flatcam.org/version"
  88. # App URL
  89. app_url = "http://flatcam.org"
  90. # Manual URL
  91. manual_url = "http://flatcam.org/manual/index.html"
  92. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  93. # this variable will hold the project status
  94. # if True it will mean that the project was modified and not saved
  95. should_we_save = False
  96. # flag is True if saving action has been triggered
  97. save_in_progress = False
  98. ##################
  99. ## Signals ##
  100. ##################
  101. # Inform the user
  102. # Handled by:
  103. # * App.info() --> Print on the status bar
  104. inform = QtCore.pyqtSignal(str)
  105. app_quit = QtCore.pyqtSignal()
  106. # General purpose background task
  107. worker_task = QtCore.pyqtSignal(dict)
  108. # File opened
  109. # Handled by:
  110. # * register_folder()
  111. # * register_recent()
  112. # Note: Setting the parameters to unicode does not seem
  113. # to have an effect. Then are received as Qstring
  114. # anyway.
  115. # File type and filename
  116. file_opened = QtCore.pyqtSignal(str, str)
  117. # File type and filename
  118. file_saved = QtCore.pyqtSignal(str, str)
  119. # Percentage of progress
  120. progress = QtCore.pyqtSignal(int)
  121. plots_updated = QtCore.pyqtSignal()
  122. # Emitted by new_object() and passes the new object as argument, plot flag.
  123. # on_object_created() adds the object to the collection, plots on appropriate flag
  124. # and emits new_object_available.
  125. object_created = QtCore.pyqtSignal(object, bool, bool)
  126. # Emitted when a object has been changed (like scaled, mirrored)
  127. object_changed = QtCore.pyqtSignal(object)
  128. # Emitted after object has been plotted.
  129. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  130. object_plotted = QtCore.pyqtSignal(object)
  131. # Emitted when a new object has been added or deleted from/to the collection
  132. object_status_changed = QtCore.pyqtSignal(object, str)
  133. message = QtCore.pyqtSignal(str, str, str)
  134. # Emmited when shell command is finished(one command only)
  135. shell_command_finished = QtCore.pyqtSignal(object)
  136. # Emitted when multiprocess pool has been recreated
  137. pool_recreated = QtCore.pyqtSignal(object)
  138. # Emitted when an unhandled exception happens
  139. # in the worker task.
  140. thread_exception = QtCore.pyqtSignal(object)
  141. def __init__(self, user_defaults=True, post_gui=None):
  142. """
  143. Starts the application.
  144. :return: app
  145. :rtype: App
  146. """
  147. App.log.info("FlatCAM Starting...")
  148. self.main_thread = QtWidgets.QApplication.instance().thread()
  149. ###################
  150. ### OS-specific ###
  151. ###################
  152. # Folder for user settings.
  153. if sys.platform == 'win32':
  154. from win32com.shell import shell, shellcon
  155. if platform.architecture()[0] == '32bit':
  156. App.log.debug("Win32!")
  157. else:
  158. App.log.debug("Win64!")
  159. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\FlatCAM'
  160. self.os = 'windows'
  161. else: # Linux/Unix/MacOS
  162. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  163. self.os = 'unix'
  164. ###############################
  165. ### Setup folders and files ###
  166. ###############################
  167. if not os.path.exists(self.data_path):
  168. os.makedirs(self.data_path)
  169. App.log.debug('Created data folder: ' + self.data_path)
  170. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  171. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  172. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  173. if not os.path.exists(self.postprocessorpaths):
  174. os.makedirs(self.postprocessorpaths)
  175. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  176. # create current_defaults.FlatConfig file if there is none
  177. try:
  178. f = open(self.data_path + '/current_defaults.FlatConfig')
  179. f.close()
  180. except IOError:
  181. App.log.debug('Creating empty current_defaults.FlatConfig')
  182. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  183. json.dump({}, f)
  184. f.close()
  185. # create factory_defaults.FlatConfig file if there is none
  186. try:
  187. f = open(self.data_path + '/factory_defaults.FlatConfig')
  188. f.close()
  189. except IOError:
  190. App.log.debug('Creating empty factory_defaults.FlatConfig')
  191. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  192. json.dump({}, f)
  193. f.close()
  194. try:
  195. f = open(self.data_path + '/recent.json')
  196. f.close()
  197. except IOError:
  198. App.log.debug('Creating empty recent.json')
  199. f = open(self.data_path + '/recent.json', 'w')
  200. json.dump([], f)
  201. f.close()
  202. # Application directory. CHDIR to it. Otherwise, trying to load
  203. # GUI icons will fail as their path is relative.
  204. # This will fail under cx_freeze ...
  205. self.app_home = os.path.dirname(os.path.realpath(__file__))
  206. App.log.debug("Application path is " + self.app_home)
  207. App.log.debug("Started in " + os.getcwd())
  208. # cx_freeze workaround
  209. if os.path.isfile(self.app_home):
  210. self.app_home = os.path.dirname(self.app_home)
  211. os.chdir(self.app_home)
  212. # Create multiprocessing pool
  213. self.pool = Pool()
  214. # variable to store mouse coordinates
  215. self.mouse = [0, 0]
  216. ####################
  217. ## Initialize GUI ##
  218. ####################
  219. # FlatCAM colors used in plotting
  220. self.FC_light_green = '#BBF268BF'
  221. self.FC_dark_green = '#006E20BF'
  222. self.FC_light_blue = '#a5a5ffbf'
  223. self.FC_dark_blue = '#0000ffbf'
  224. QtCore.QObject.__init__(self)
  225. self.ui = FlatCAMGUI(self.version, self.beta, self)
  226. # self.connect(self.ui,
  227. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  228. # self.save_geometry) PyQt4
  229. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  230. self.ui.final_save.connect(self.final_save)
  231. ##############
  232. #### Data ####
  233. ##############
  234. self.recent = []
  235. self.clipboard = QtWidgets.QApplication.clipboard()
  236. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  237. self.project_filename = None
  238. self.toggle_units_ignore = False
  239. # self.defaults_form = PreferencesUI()
  240. # when adding entries here read the comments in the method found bellow named:
  241. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  242. self.defaults_form_fields = {
  243. # General App
  244. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  245. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  246. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  247. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  248. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  249. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  250. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  251. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  252. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  253. "global_project_autohide": self.ui.general_defaults_form.general_app_group.project_autohide_cb,
  254. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_group.toggle_tooltips_cb,
  255. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  256. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  257. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  258. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  259. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  260. # General GUI Preferences
  261. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  262. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  263. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  264. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  265. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  266. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  267. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  268. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  269. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  270. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  271. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  272. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  273. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  274. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  275. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  276. # General GUI Settings
  277. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  278. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  279. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  280. # Gerber General
  281. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  282. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  283. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  284. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  285. # Gerber Options
  286. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  287. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  288. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  289. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  290. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  291. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  292. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  293. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  294. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  295. # Gerber Advanced Options
  296. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  297. "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  298. "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  299. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  300. # Gerber Export
  301. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  302. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  303. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  304. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  305. # Excellon General
  306. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  307. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  308. "excellon_format_upper_in": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  309. "excellon_format_lower_in": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  310. "excellon_format_upper_mm": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  311. "excellon_format_lower_mm": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  312. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  313. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  314. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  315. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  316. # Excellon Options
  317. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  318. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  319. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  320. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  321. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_opt_group.spindledir_radio,
  322. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  323. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  324. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  325. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  326. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  327. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  328. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  329. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  330. # Excellon Advanced Options
  331. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  332. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  333. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  334. "excellon_endz": self.ui.excellon_defaults_form.excellon_adv_opt_group.eendz_entry,
  335. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  336. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  337. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  338. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  339. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  340. # Excellon Export
  341. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  342. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  343. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  344. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  345. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  346. # Geometry General
  347. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  348. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  349. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  350. # Geometry Options
  351. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  352. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  353. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  354. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  355. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  356. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_opt_group.spindledir_radio,
  357. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  358. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  359. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  360. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  361. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  362. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  363. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  364. # Geometry Advanced Options
  365. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  366. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  367. "geometry_endz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gendz_entry,
  368. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  369. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  370. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  371. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  372. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  373. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  374. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  375. # CNCJob General
  376. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  377. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  378. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  379. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  380. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  381. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  382. # CNC Job Options
  383. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  384. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  385. # CNC Job Advanced Options
  386. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  387. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  388. # NCC Tool
  389. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  390. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  391. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  392. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  393. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  394. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  395. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  396. # CutOut Tool
  397. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  398. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  399. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  400. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  401. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  402. # Paint Area Tool
  403. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  404. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  405. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  406. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  407. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  408. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  409. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  410. # 2-sided Tool
  411. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  412. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  413. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  414. # Film Tool
  415. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  416. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  417. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  418. # Panelize Tool
  419. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  420. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  421. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  422. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  423. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  424. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  425. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  426. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  427. # Calculators Tool
  428. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  429. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  430. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  431. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  432. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  433. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  434. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  435. # Transformations Tool
  436. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  437. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  438. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  439. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  440. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  441. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  442. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  443. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  444. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  445. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  446. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  447. # SolderPaste Dispensing Tool
  448. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  449. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  450. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  451. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  452. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  453. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  454. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  455. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  456. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  457. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  458. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  459. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  460. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  461. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  462. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  463. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo
  464. }
  465. #############################
  466. #### LOAD POSTPROCESSORS ####
  467. #############################
  468. self.postprocessors = load_postprocessors(self)
  469. for name in list(self.postprocessors.keys()):
  470. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  471. if name.partition('_')[0] == 'Paste':
  472. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  473. continue
  474. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  475. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  476. if name == 'hpgl':
  477. continue
  478. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  479. #############################
  480. #### LOAD LANGUAGES ####
  481. #############################
  482. self.languages = fcTranslate.load_languages()
  483. for name in sorted(self.languages.values()):
  484. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  485. self.defaults = LoudDict()
  486. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  487. self.defaults.update({
  488. # Global APP Preferences
  489. "global_serial": 0,
  490. "global_stats": {},
  491. "units": "IN",
  492. "global_app_level": 'b',
  493. "global_language": 'English',
  494. "global_version_check": True,
  495. "global_send_stats": True,
  496. "global_pan_button": '2',
  497. "global_mselect_key": 'Control',
  498. "global_project_at_startup": False,
  499. "global_project_autohide": True,
  500. "global_toggle_tooltips": True,
  501. "global_worker_number": 2,
  502. "global_tolerance": 0.01,
  503. "global_open_style": True,
  504. "global_compression_level": 3,
  505. "global_save_compressed": True,
  506. # Global GUI Preferences
  507. "global_gridx": 0.0393701,
  508. "global_gridy": 0.0393701,
  509. "global_snap_max": 0.001968504,
  510. "global_workspace": False,
  511. "global_workspaceT": "A4P",
  512. "global_grid_context_menu": {
  513. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  514. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  515. },
  516. "global_plot_fill": '#BBF268BF',
  517. "global_plot_line": '#006E20BF',
  518. "global_sel_fill": '#a5a5ffbf',
  519. "global_sel_line": '#0000ffbf',
  520. "global_alt_sel_fill": '#BBF268BF',
  521. "global_alt_sel_line": '#006E20BF',
  522. "global_draw_color": '#FF0000',
  523. "global_sel_draw_color": '#0000FF',
  524. "global_proj_item_color": '#000000',
  525. "global_proj_item_dis_color": '#b7b7cb',
  526. "global_toolbar_view": 511,
  527. "global_background_timeout": 300000, # Default value is 5 minutes
  528. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  529. # (python trace only for unknown errors),
  530. # 1 = show trace(show trace allways),
  531. # 2 = (For the future).
  532. # Persistence
  533. "global_last_folder": None,
  534. "global_last_save_folder": None,
  535. # Default window geometry
  536. "global_def_win_x": 100,
  537. "global_def_win_y": 100,
  538. "global_def_win_w": 1024,
  539. "global_def_win_h": 650,
  540. "global_def_notebook_width": 1,
  541. # Constants...
  542. "global_defaults_save_period_ms": 20000, # Time between default saves.
  543. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  544. "global_shell_at_startup": False, # Show the shell at startup.
  545. "global_recent_limit": 10, # Max. items in recent list.
  546. "fit_key": 'V',
  547. "zoom_out_key": '-',
  548. "zoom_in_key": '=',
  549. "grid_toggle_key": 'G',
  550. "zoom_ratio": 1.5,
  551. "global_point_clipboard_format": "(%.4f, %.4f)",
  552. "global_zdownrate": None,
  553. # General GUI Settings
  554. "global_hover": False,
  555. "global_selection_shape": True,
  556. "global_layout": "compact",
  557. # Gerber General
  558. "gerber_plot": True,
  559. "gerber_solid": True,
  560. "gerber_multicolored": False,
  561. "gerber_isotooldia": 0.016,
  562. "gerber_isopasses": 1,
  563. "gerber_isooverlap": 0.15,
  564. # Gerber Options
  565. "gerber_combine_passes": False,
  566. "gerber_milling_type": "cl",
  567. "gerber_noncoppermargin": 0.1,
  568. "gerber_noncopperrounded": False,
  569. "gerber_bboxmargin": 0.1,
  570. "gerber_bboxrounded": False,
  571. "gerber_circle_steps": 128,
  572. "gerber_use_buffer_for_union": True,
  573. # Gerber Advanced Options
  574. "gerber_aperture_display": False,
  575. "gerber_aperture_scale_factor": 1.0,
  576. "gerber_aperture_buffer_factor": 0.0,
  577. "gerber_follow": False,
  578. # Gerber Export
  579. "gerber_exp_units": 'IN',
  580. "gerber_exp_integer": 2,
  581. "gerber_exp_decimals": 4,
  582. "gerber_exp_zeros": 'L',
  583. # Excellon General
  584. "excellon_plot": True,
  585. "excellon_solid": True,
  586. "excellon_format_upper_in": 2,
  587. "excellon_format_lower_in": 4,
  588. "excellon_format_upper_mm": 3,
  589. "excellon_format_lower_mm": 3,
  590. "excellon_zeros": "L",
  591. "excellon_units": "INCH",
  592. "excellon_optimization_type": 'B',
  593. "excellon_search_time": 3,
  594. # Excellon Options
  595. "excellon_drillz": -0.1,
  596. "excellon_travelz": 0.1,
  597. "excellon_feedrate": 3.0,
  598. "excellon_spindlespeed": None,
  599. "excellon_spindledir": 'CW',
  600. "excellon_dwell": False,
  601. "excellon_dwelltime": 1,
  602. "excellon_toolchange": False,
  603. "excellon_toolchangez": 0.5,
  604. "excellon_ppname_e": 'default',
  605. "excellon_tooldia": 0.016,
  606. "excellon_slot_tooldia": 0.016,
  607. "excellon_gcode_type": "drills",
  608. # Excellon Advanced Options
  609. "excellon_offset": 0.0,
  610. "excellon_toolchangexy": "0.0, 0.0",
  611. "excellon_startz": None,
  612. "excellon_endz": 0.5,
  613. "excellon_feedrate_rapid": 3.0,
  614. "excellon_z_pdepth": -0.02,
  615. "excellon_feedrate_probe": 3.0,
  616. "excellon_f_plunge": False,
  617. "excellon_f_retract": False,
  618. # Excellon Export
  619. "excellon_exp_units": 'INCH',
  620. "excellon_exp_format": 'ndec',
  621. "excellon_exp_integer": 2,
  622. "excellon_exp_decimals": 4,
  623. "excellon_exp_zeros": 'LZ',
  624. # Geometry General
  625. "geometry_plot": True,
  626. "geometry_circle_steps": 128,
  627. "geometry_cnctooldia": 0.016,
  628. # Geometry Options
  629. "geometry_cutz": -0.002,
  630. "geometry_multidepth": False,
  631. "geometry_depthperpass": 0.002,
  632. "geometry_travelz": 0.1,
  633. "geometry_toolchange": False,
  634. "geometry_toolchangez": 0.5,
  635. "geometry_feedrate": 3.0,
  636. "geometry_feedrate_z": 3.0,
  637. "geometry_spindlespeed": None,
  638. "geometry_spindledir": 'CW',
  639. "geometry_dwell": False,
  640. "geometry_dwelltime": 1,
  641. "geometry_ppname_g": 'default',
  642. # Geometry Advanced Options
  643. "geometry_toolchangexy": "0.0, 0.0",
  644. "geometry_startz": None,
  645. "geometry_endz": 0.5,
  646. "geometry_feedrate_rapid": 3.0,
  647. "geometry_extracut": False,
  648. "geometry_z_pdepth": -0.02,
  649. "geometry_f_plunge": False,
  650. "geometry_feedrate_probe": 3.0,
  651. "geometry_segx": 0.0,
  652. "geometry_segy": 0.0,
  653. # CNC Job General
  654. "cncjob_plot": True,
  655. "cncjob_plot_kind": 'all',
  656. "cncjob_tooldia": 0.0393701,
  657. "cncjob_coords_decimals": 4,
  658. "cncjob_fr_decimals": 2,
  659. "cncjob_steps_per_circle": 64,
  660. # CNC Job Options
  661. "cncjob_prepend": "",
  662. "cncjob_append": "",
  663. # CNC Job Advanced Options
  664. "cncjob_toolchange_macro": "",
  665. "cncjob_toolchange_macro_enable": False,
  666. "tools_ncctools": "0.0393701, 0.019685",
  667. "tools_nccoverlap": 0.015748,
  668. "tools_nccmargin": 0.00393701,
  669. "tools_nccmethod": "seed",
  670. "tools_nccconnect": True,
  671. "tools_ncccontour": True,
  672. "tools_nccrest": False,
  673. "tools_cutouttooldia": 0.00393701,
  674. "tools_cutoutmargin": 0.00393701,
  675. "tools_cutoutgapsize": 0.005905512,
  676. "tools_gaps_ff": "8",
  677. "tools_cutout_convexshape": False,
  678. "tools_painttooldia": 0.07,
  679. "tools_paintoverlap": 0.15,
  680. "tools_paintmargin": 0.0,
  681. "tools_paintmethod": "seed",
  682. "tools_selectmethod": "single",
  683. "tools_pathconnect": True,
  684. "tools_paintcontour": True,
  685. "tools_2sided_mirror_axis": "X",
  686. "tools_2sided_axis_loc": "point",
  687. "tools_2sided_drilldia": 0.0393701,
  688. "tools_film_type": 'neg',
  689. "tools_film_boundary": 0.0393701,
  690. "tools_film_scale": 0,
  691. "tools_panelize_spacing_columns": 0,
  692. "tools_panelize_spacing_rows": 0,
  693. "tools_panelize_columns": 1,
  694. "tools_panelize_rows": 1,
  695. "tools_panelize_constrain": False,
  696. "tools_panelize_constrainx": 0.0,
  697. "tools_panelize_constrainy": 0.0,
  698. "tools_panelize_panel_type": 'gerber',
  699. "tools_calc_vshape_tip_dia": 0.007874,
  700. "tools_calc_vshape_tip_angle": 30,
  701. "tools_calc_vshape_cut_z": 0.000787,
  702. "tools_calc_electro_length": 10.0,
  703. "tools_calc_electro_width": 10.0,
  704. "tools_calc_electro_cdensity":13.0,
  705. "tools_calc_electro_growth": 10.0,
  706. "tools_transform_rotate": 90,
  707. "tools_transform_skew_x": 0.0,
  708. "tools_transform_skew_y": 0.0,
  709. "tools_transform_scale_x": 1.0,
  710. "tools_transform_scale_y": 1.0,
  711. "tools_transform_scale_link": True,
  712. "tools_transform_scale_reference": True,
  713. "tools_transform_offset_x": 0.0,
  714. "tools_transform_offset_y": 0.0,
  715. "tools_transform_mirror_reference": False,
  716. "tools_transform_mirror_point": (0, 0),
  717. "tools_solderpaste_tools": "0.0393701, 0.011811",
  718. "tools_solderpaste_new": 0.011811,
  719. "tools_solderpaste_z_start": 0.00019685039,
  720. "tools_solderpaste_z_dispense": 0.00393701,
  721. "tools_solderpaste_z_stop": 0.00019685039,
  722. "tools_solderpaste_z_travel": 0.00393701,
  723. "tools_solderpaste_z_toolchange": 0.0393701,
  724. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  725. "tools_solderpaste_frxy": 3.0,
  726. "tools_solderpaste_frz": 3.0,
  727. "tools_solderpaste_frz_dispense": 0.0393701,
  728. "tools_solderpaste_speedfwd": 20,
  729. "tools_solderpaste_dwellfwd": 1,
  730. "tools_solderpaste_speedrev": 10,
  731. "tools_solderpaste_dwellrev": 1,
  732. "tools_solderpaste_pp": 'Paste_1'
  733. })
  734. ###############################
  735. ### Load defaults from file ###
  736. ###############################
  737. if user_defaults:
  738. self.load_defaults(filename='current_defaults')
  739. ############################
  740. ##### APPLY APP LANGUAGE ###
  741. ############################
  742. ret_val = fcTranslate.apply_language('strings')
  743. if ret_val == "no language":
  744. self.inform.emit(_("[ERROR] Could not find the Language files. The App strings are missing."))
  745. log.debug("Could not find the Language files. The App strings are missing.")
  746. else:
  747. # make the current language the current selection on the language combobox
  748. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  749. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  750. ###################################
  751. ### CREATE UNIQUE SERIAL NUMBER ###
  752. ###################################
  753. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  754. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  755. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  756. self.save_defaults(silent=True)
  757. self.propagate_defaults(silent=True)
  758. self.restore_main_win_geom()
  759. def auto_save_defaults():
  760. try:
  761. self.save_defaults(silent=True)
  762. self.propagate_defaults(silent=True)
  763. finally:
  764. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  765. # the following lines activates automatic defaults save
  766. # if user_defaults:
  767. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  768. # self.options_form = PreferencesUI()
  769. self.options_form_fields = {
  770. "units": self.ui.general_options_form.general_app_group.units_radio,
  771. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  772. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  773. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  774. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  775. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  776. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  777. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  778. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  779. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  780. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  781. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  782. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  783. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  784. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  785. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  786. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  787. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  788. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  789. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  790. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  791. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  792. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  793. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  794. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  795. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  796. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  797. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  798. "excellon_spindledir": self.ui.excellon_options_form.excellon_opt_group.spindledir_radio,
  799. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  800. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  801. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  802. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  803. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  804. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  805. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  806. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  807. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  808. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  809. "excellon_endz": self.ui.excellon_options_form.excellon_adv_opt_group.eendz_entry,
  810. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  811. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  812. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  813. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  814. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  815. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  816. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  817. "geometry_spindledir": self.ui.geometry_options_form.geometry_opt_group.spindledir_radio,
  818. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  819. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  820. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  821. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  822. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  823. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  824. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  825. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  826. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  827. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  828. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  829. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  830. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  831. "geometry_endz": self.ui.geometry_options_form.geometry_adv_opt_group.gendz_entry,
  832. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  833. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  834. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  835. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  836. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  837. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  838. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  839. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  840. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  841. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  842. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  843. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  844. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  845. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  846. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  847. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  848. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  849. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  850. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  851. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  852. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  853. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  854. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  855. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  856. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  857. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  858. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  859. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  860. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  861. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  862. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  863. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  864. }
  865. for name in list(self.postprocessors.keys()):
  866. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  867. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  868. self.options = LoudDict()
  869. self.options.set_change_callback(self.on_options_dict_change)
  870. self.options.update({
  871. "units": "IN",
  872. "global_gridx": 1.0,
  873. "global_gridy": 1.0,
  874. "global_snap_max": 0.05,
  875. "global_background_timeout": 300000, # Default value is 5 minutes
  876. "global_verbose_error_level": 0, # Shell verbosity:
  877. # 0 = default(python trace only for unknown errors),
  878. # 1 = show trace(show trace allways), 2 = (For the future).
  879. "gerber_plot": True,
  880. "gerber_solid": True,
  881. "gerber_multicolored": False,
  882. "gerber_isotooldia": 0.016,
  883. "gerber_isopasses": 1,
  884. "gerber_isooverlap": 0.15,
  885. "gerber_combine_passes": True,
  886. "gerber_noncoppermargin": 0.0,
  887. "gerber_noncopperrounded": False,
  888. "gerber_bboxmargin": 0.0,
  889. "gerber_bboxrounded": False,
  890. "excellon_plot": True,
  891. "excellon_solid": False,
  892. "excellon_format_upper_in": 2,
  893. "excellon_format_lower_in": 4,
  894. "excellon_format_upper_mm": 3,
  895. "excellon_format_lower_mm": 3,
  896. "excellon_units": 'INCH',
  897. "excellon_optimization_type": 'B',
  898. "excellon_search_time": 3,
  899. "excellon_zeros": "L",
  900. "excellon_drillz": -0.1,
  901. "excellon_travelz": 0.1,
  902. "excellon_feedrate": 3.0,
  903. "excellon_feedrate_rapid": 3.0,
  904. "excellon_spindlespeed": None,
  905. "excellon_spindledir": 'CW',
  906. "excellon_dwell": True,
  907. "excellon_dwelltime": 1000,
  908. "excellon_toolchange": False,
  909. "excellon_toolchangez": 1.0,
  910. "excellon_toolchangexy": "0.0, 0.0",
  911. "excellon_tooldia": 0.016,
  912. "excellon_ppname_e": 'default',
  913. "excellon_f_plunge": False,
  914. "excellon_startz": None,
  915. "excellon_endz": 2.0,
  916. "geometry_plot": True,
  917. "geometry_segx": 0.0,
  918. "geometry_segy": 0.0,
  919. "geometry_cutz": -0.002,
  920. "geometry_travelz": 0.1,
  921. "geometry_feedrate": 3.0,
  922. "geometry_feedrate_z": 3.0,
  923. "geometry_feedrate_rapid": 3.0,
  924. "geometry_spindlespeed": None,
  925. "geometry_spindledir": 'CW',
  926. "geometry_dwell": True,
  927. "geometry_dwelltime": 1000,
  928. "geometry_cnctooldia": 0.016,
  929. "geometry_toolchange": False,
  930. "geometry_toolchangez": 2.0,
  931. "geometry_toolchangexy": "0.0, 0.0",
  932. "geometry_startz": None,
  933. "geometry_endz": 2.0,
  934. "geometry_ppname_g": "default",
  935. "geometry_f_plunge": False,
  936. "geometry_depthperpass": 0.002,
  937. "geometry_multidepth": False,
  938. "geometry_extracut": False,
  939. "cncjob_plot": True,
  940. "cncjob_tooldia": 0.016,
  941. "cncjob_prepend": "",
  942. "cncjob_append": "",
  943. "tools_ncctools": "1.0, 0.5",
  944. "tools_nccoverlap": 0.4,
  945. "tools_nccmargin": 1,
  946. "tools_cutouttooldia": 0.07,
  947. "tools_cutoutmargin": 0.1,
  948. "tools_cutoutgapsize": 0.15,
  949. "tools_gaps_ff": "8",
  950. "tools_painttooldia": 0.07,
  951. "tools_paintoverlap": 0.15,
  952. "tools_paintmargin": 0.0,
  953. "tools_paintmethod": "seed",
  954. "tools_selectmethod": "single",
  955. "tools_pathconnect": True,
  956. "tools_paintcontour": True,
  957. "tools_2sided_mirror_axis": "X",
  958. "tools_2sided_axis_loc": 'point',
  959. "tools_2sided_drilldia": 1,
  960. "tools_film_type": 'neg',
  961. "tools_film_boundary": 1,
  962. "tools_film_scale": 0,
  963. "tools_panelize_spacing_columns": 0,
  964. "tools_panelize_spacing_rows": 0,
  965. "tools_panelize_columns": 1,
  966. "tools_panelize_rows": 1,
  967. "tools_panelize_constrain": False,
  968. "tools_panelize_constrainx": 0.0,
  969. "tools_panelize_constrainy": 0.0
  970. })
  971. self.options.update(self.defaults) # Copy app defaults to project options
  972. self.gen_form = None
  973. self.ger_form = None
  974. self.exc_form = None
  975. self.geo_form = None
  976. self.cnc_form = None
  977. self.tools_form = None
  978. self.on_options_combo_change(0) # Will show the initial form
  979. ### Define OBJECT COLLECTION ###
  980. self.collection = ObjectCollection(self)
  981. self.ui.project_tab_layout.addWidget(self.collection.view)
  982. ###
  983. self.log.debug("Finished creating Object Collection.")
  984. ### Initialize the color box's color in Preferences -> Global -> Color
  985. # Init Plot Colors
  986. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  987. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  988. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  989. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  990. int(self.defaults['global_plot_fill'][7:9], 16))
  991. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  992. int(self.defaults['global_plot_fill'][7:9], 16))
  993. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  994. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  995. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  996. # Init Left-Right Selection colors
  997. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  998. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  999. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1000. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1001. int(self.defaults['global_sel_fill'][7:9], 16))
  1002. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1003. int(self.defaults['global_sel_fill'][7:9], 16))
  1004. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1005. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1006. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1007. # Init Right-Left Selection colors
  1008. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1009. self.defaults['global_alt_sel_fill'])
  1010. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1011. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1012. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1013. int(self.defaults['global_sel_fill'][7:9], 16))
  1014. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1015. int(self.defaults['global_sel_fill'][7:9], 16))
  1016. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1017. self.defaults['global_alt_sel_line'])
  1018. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1019. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1020. # Init Draw color and Selection Draw Color
  1021. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1022. self.defaults['global_draw_color'])
  1023. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1024. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1025. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1026. self.defaults['global_sel_draw_color'])
  1027. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1028. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1029. # Init Project Items color
  1030. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1031. self.defaults['global_proj_item_color'])
  1032. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1033. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1034. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1035. self.defaults['global_proj_item_dis_color'])
  1036. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1037. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1038. #### End of Data ####
  1039. #### Plot Area ####
  1040. start_plot_time = time.time() # debug
  1041. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  1042. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  1043. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  1044. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  1045. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  1046. # Keys over plot enabled
  1047. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  1048. self.ui.splitter.setStretchFactor(1, 2)
  1049. # So it can receive key presses
  1050. self.plotcanvas.vispy_canvas.native.setFocus()
  1051. self.app_cursor = self.plotcanvas.new_cursor()
  1052. self.app_cursor.enabled = False
  1053. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1054. # depending on from where those tools are called different actions can be done
  1055. self.call_source = 'app'
  1056. end_plot_time = time.time()
  1057. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  1058. ### EDITOR section
  1059. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  1060. self.exc_editor = FlatCAMExcEditor(self)
  1061. self.grb_editor = FlatCAMGrbEditor(self)
  1062. #### Adjust tabs width ####
  1063. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1064. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1065. self.collection.view.setMinimumWidth(290)
  1066. self.log.debug("Finished adding FlatCAM Editor's.")
  1067. #### Worker ####
  1068. if self.defaults["global_worker_number"]:
  1069. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1070. else:
  1071. self.workers = WorkerStack(workers_number=2)
  1072. self.worker_task.connect(self.workers.add_task)
  1073. ### Signal handling ###
  1074. ## Custom signals
  1075. self.inform.connect(self.info)
  1076. self.app_quit.connect(self.quit_application)
  1077. self.message.connect(self.message_dialog)
  1078. self.progress.connect(self.set_progress_bar)
  1079. self.object_created.connect(self.on_object_created)
  1080. self.object_changed.connect(self.on_object_changed)
  1081. self.object_plotted.connect(self.on_object_plotted)
  1082. self.plots_updated.connect(self.on_plots_updated)
  1083. self.file_opened.connect(self.register_recent)
  1084. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1085. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1086. ## Standard signals
  1087. # Menu
  1088. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1089. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1090. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1091. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1092. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1093. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1094. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1095. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1096. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1097. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1098. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1099. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1100. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1101. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1102. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1103. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1104. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1105. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1106. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1107. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1108. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1109. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1110. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1111. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1112. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1113. self.ui.menufile_exit.triggered.connect(self.final_save)
  1114. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1115. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1116. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1117. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1118. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1119. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1120. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1121. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1122. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1123. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1124. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1125. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1126. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1127. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1128. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1129. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1130. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1131. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1132. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1133. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1134. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1135. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1136. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1137. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1138. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1139. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1140. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1141. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1142. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1143. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1144. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1145. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1146. self.ui.menuview_zoom_in.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1147. self.ui.menuview_zoom_out.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1148. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1149. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1150. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1151. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1152. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1153. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1154. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1155. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1156. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1157. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1158. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1159. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1160. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1161. self.ui.menuprojectenable.triggered.connect(lambda: self.enable_plots(self.collection.get_selected()))
  1162. self.ui.menuprojectdisable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  1163. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1164. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1165. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1166. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1167. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1168. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1169. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1170. # ToolBar signals
  1171. self.connect_toolbar_signals()
  1172. # Context Menu
  1173. self.ui.popmenu_disable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  1174. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1175. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1176. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1177. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1178. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1179. self.ui.clearplot.triggered.connect(self.clear_plots)
  1180. self.ui.replot.triggered.connect(self.plot_all)
  1181. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1182. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1183. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1184. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1185. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1186. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1187. # Preferences Plot Area TAB
  1188. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1189. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1190. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1191. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1192. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1193. ###############################
  1194. ### GUI PREFERENCES SIGNALS ###
  1195. ###############################
  1196. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1197. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1198. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1199. )
  1200. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1201. lambda :self.on_toggle_units(no_pref=False))
  1202. ###############################
  1203. ### GUI PREFERENCES SIGNALS ###
  1204. ###############################
  1205. # Setting plot colors signals
  1206. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1207. self.on_pf_color_entry)
  1208. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1209. self.on_pf_color_button)
  1210. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1211. self.on_pf_color_spinner)
  1212. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1213. self.on_pf_color_slider)
  1214. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1215. self.on_pl_color_entry)
  1216. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1217. self.on_pl_color_button)
  1218. # Setting selection (left - right) colors signals
  1219. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1220. self.on_sf_color_entry)
  1221. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1222. self.on_sf_color_button)
  1223. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1224. self.on_sf_color_spinner)
  1225. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1226. self.on_sf_color_slider)
  1227. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1228. self.on_sl_color_entry)
  1229. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1230. self.on_sl_color_button)
  1231. # Setting selection (right - left) colors signals
  1232. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1233. self.on_alt_sf_color_entry)
  1234. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1235. self.on_alt_sf_color_button)
  1236. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1237. self.on_alt_sf_color_spinner)
  1238. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1239. self.on_alt_sf_color_slider)
  1240. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1241. self.on_alt_sl_color_entry)
  1242. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1243. self.on_alt_sl_color_button)
  1244. # Setting Editor Draw colors signals
  1245. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1246. self.on_draw_color_entry)
  1247. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1248. self.on_draw_color_button)
  1249. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1250. self.on_sel_draw_color_entry)
  1251. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1252. self.on_sel_draw_color_button)
  1253. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1254. self.on_proj_color_entry)
  1255. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1256. self.on_proj_color_button)
  1257. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1258. self.on_proj_color_dis_entry)
  1259. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1260. self.on_proj_color_dis_button)
  1261. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1262. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1263. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1264. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1265. self.on_cnc_custom_parameters)
  1266. # Modify G-CODE Plot Area TAB
  1267. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1268. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1269. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1270. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1271. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1272. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1273. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1274. # Object list
  1275. self.collection.view.activated.connect(self.on_row_activated)
  1276. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1277. self.ui.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1278. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1279. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1280. self.on_excellon_defaults_button)
  1281. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1282. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1283. self.on_excellon_options_button)
  1284. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1285. self.tool_tab_locked = False
  1286. # decide if to show or hide the Notebook side of the screen at startup
  1287. if self.defaults["global_project_at_startup"] is True:
  1288. self.ui.splitter.setSizes([1, 1])
  1289. else:
  1290. self.ui.splitter.setSizes([0, 1])
  1291. ####################
  1292. ### Other setups ###
  1293. ####################
  1294. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1295. self.setup_obj_classes()
  1296. self.setup_recent_items()
  1297. self.setup_component_editor()
  1298. #############
  1299. ### Shell ###
  1300. #############
  1301. ###
  1302. # Auto-complete KEYWORDS
  1303. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1304. 'aligndrill', 'clear',
  1305. 'aligndrillgrid', 'cncjob', 'cutout', 'delete', 'drillcncjob',
  1306. 'export_gcode',
  1307. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  1308. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  1309. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  1310. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  1311. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  1312. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  1313. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  1314. ]
  1315. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  1316. 'holes','grid', 'minoffset', 'gridoffset','axisoffset', 'dia', 'dist', 'gridoffsetx',
  1317. 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate', 'feedrate_rapid',
  1318. 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g', 'outname', 'margin',
  1319. 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed', 'toolchange',
  1320. 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble', 'filename',
  1321. 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads', 'x', 'y',
  1322. 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value', 'angle_x',
  1323. 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1324. ]
  1325. self.tcl_keywords = [
  1326. "after", "append", "apply", "array", "auto_execok", "auto_import", "auto_load", "auto_mkindex",
  1327. "auto_qualify", "auto_reset", "bgerror", "binary", "break", "case", "catch", "cd", "chan", "clock", "close",
  1328. "concat", "continue", "coroutine", "dict", "encoding", "eof", "error", "eval", "exec", "exit", "expr",
  1329. "fblocked", "fconfigure", "fcopy", "file", "fileevent", "flush", "for", "foreach", "format", "gets", "glob",
  1330. "global", "history", "if", "incr", "info", "interp", "join", "lappend", "lassign", "lindex", "linsert",
  1331. "list", "llength", "load", "lrange", "lrepeat", "lreplace", "lreverse", "lsearch", "lset", "lsort",
  1332. "mathfunc", "mathop", "memory", "my", "namespace", "next", "nextto", "open", "package", "parray", "pid",
  1333. "pkg_mkIndex", "platform", "proc", "puts", "pwd", "read", "refchan", "regexp", "regsub", "rename", "return",
  1334. "scan", "seek", "self", "set", "socket", "source", "split", "string", "subst", "switch", "tailcall",
  1335. "tcl_endOfWord", "tcl_findLibrary", "tcl_startOfNextWord", "tcl_startOfPreviousWord", "tcl_wordBreakAfter",
  1336. "tcl_wordBreakBefore", "tell", "throw", "time", "tm", "trace", "transchan", "try", "unknown", "unload",
  1337. "unset", "update", "uplevel", "upvar", "variable", "vwait", "while", "yield", "yieldto", "zlib",
  1338. "attemptckalloc", "attemptckrealloc", "ckalloc", "ckfree", "ckrealloc", "Tcl_Access", "Tcl_AddErrorInfo",
  1339. "Tcl_AddObjErrorInfo", "Tcl_AlertNotifier", "Tcl_Alloc", "Tcl_AllocStatBuf", "Tcl_AllowExceptions",
  1340. "Tcl_AppendAllObjTypes", "Tcl_AppendElement", "Tcl_AppendExportList", "Tcl_AppendFormatToObj",
  1341. "Tcl_AppendLimitedToObj", "Tcl_AppendObjToErrorInfo", "Tcl_AppendObjToObj", "Tcl_AppendPrintfToObj",
  1342. "Tcl_AppendResult", "Tcl_AppendResultVA", "Tcl_AppendStringsToObj", "Tcl_AppendStringsToObjVA",
  1343. "Tcl_AppendToObj", "Tcl_AppendUnicodeToObj", "Tcl_AppInit", "Tcl_AsyncCreate", "Tcl_AsyncDelete",
  1344. "Tcl_AsyncInvoke", "Tcl_AsyncMark", "Tcl_AsyncReady", "Tcl_AttemptAlloc", "Tcl_AttemptRealloc",
  1345. "Tcl_AttemptSetObjLength", "Tcl_BackgroundError", "Tcl_BackgroundException", "Tcl_Backslash",
  1346. "Tcl_BadChannelOption", "Tcl_CallWhenDeleted", "Tcl_Canceled", "Tcl_CancelEval", "Tcl_CancelIdleCall",
  1347. "Tcl_ChannelBlockModeProc", "Tcl_ChannelBuffered", "Tcl_ChannelClose2Proc", "Tcl_ChannelCloseProc",
  1348. "Tcl_ChannelFlushProc", "Tcl_ChannelGetHandleProc", "Tcl_ChannelGetOptionProc", "Tcl_ChannelHandlerProc",
  1349. "Tcl_ChannelInputProc", "Tcl_ChannelName", "Tcl_ChannelOutputProc", "Tcl_ChannelSeekProc",
  1350. "Tcl_ChannelSetOptionProc", "Tcl_ChannelThreadActionProc", "Tcl_ChannelTruncateProc", "Tcl_ChannelVersion",
  1351. "Tcl_ChannelWatchProc", "Tcl_ChannelWideSeekProc", "Tcl_Chdir", "Tcl_ClassGetMetadata",
  1352. "Tcl_ClassSetConstructor", "Tcl_ClassSetDestructor", "Tcl_ClassSetMetadata", "Tcl_ClearChannelHandlers",
  1353. "Tcl_Close", "Tcl_CommandComplete", "Tcl_CommandTraceInfo", "Tcl_Concat", "Tcl_ConcatObj",
  1354. "Tcl_ConditionFinalize", "Tcl_ConditionNotify", "Tcl_ConditionWait", "Tcl_ConvertCountedElement",
  1355. "Tcl_ConvertElement", "Tcl_ConvertToType", "Tcl_CopyObjectInstance", "Tcl_CreateAlias",
  1356. "Tcl_CreateAliasObj", "Tcl_CreateChannel", "Tcl_CreateChannelHandler", "Tcl_CreateCloseHandler",
  1357. "Tcl_CreateCommand", "Tcl_CreateEncoding", "Tcl_CreateEnsemble", "Tcl_CreateEventSource",
  1358. "Tcl_CreateExitHandler", "Tcl_CreateFileHandler", "Tcl_CreateHashEntry", "Tcl_CreateInterp",
  1359. "Tcl_CreateMathFunc", "Tcl_CreateNamespace", "Tcl_CreateObjCommand", "Tcl_CreateObjTrace",
  1360. "Tcl_CreateSlave", "Tcl_CreateThread", "Tcl_CreateThreadExitHandler", "Tcl_CreateTimerHandler",
  1361. "Tcl_CreateTrace", "Tcl_CutChannel", "Tcl_DecrRefCount", "Tcl_DeleteAssocData", "Tcl_DeleteChannelHandler",
  1362. "Tcl_DeleteCloseHandler", "Tcl_DeleteCommand", "Tcl_DeleteCommandFromToken", "Tcl_DeleteEvents",
  1363. "Tcl_DeleteEventSource", "Tcl_DeleteExitHandler", "Tcl_DeleteFileHandler", "Tcl_DeleteHashEntry",
  1364. "Tcl_DeleteHashTable", "Tcl_DeleteInterp", "Tcl_DeleteNamespace", "Tcl_DeleteThreadExitHandler",
  1365. "Tcl_DeleteTimerHandler", "Tcl_DeleteTrace", "Tcl_DetachChannel", "Tcl_DetachPids", "Tcl_DictObjDone",
  1366. "Tcl_DictObjFirst", "Tcl_DictObjGet", "Tcl_DictObjNext", "Tcl_DictObjPut", "Tcl_DictObjPutKeyList",
  1367. "Tcl_DictObjRemove", "Tcl_DictObjRemoveKeyList", "Tcl_DictObjSize", "Tcl_DiscardInterpState",
  1368. "Tcl_DiscardResult", "Tcl_DontCallWhenDeleted", "Tcl_DoOneEvent", "Tcl_DoWhenIdle", "Tcl_DStringAppend",
  1369. "Tcl_DStringAppendElement", "Tcl_DStringEndSublist", "Tcl_DStringFree", "Tcl_DStringGetResult",
  1370. "Tcl_DStringInit", "Tcl_DStringLength", "Tcl_DStringResult", "Tcl_DStringSetLength",
  1371. "Tcl_DStringStartSublist", "Tcl_DStringTrunc", "Tcl_DStringValue", "Tcl_DumpActiveMemory",
  1372. "Tcl_DuplicateObj", "Tcl_Eof", "Tcl_ErrnoId", "Tcl_ErrnoMsg", "Tcl_Eval", "Tcl_EvalEx", "Tcl_EvalFile",
  1373. "Tcl_EvalObjEx", "Tcl_EvalObjv", "Tcl_EvalTokens", "Tcl_EvalTokensStandard", "Tcl_EventuallyFree",
  1374. "Tcl_Exit", "Tcl_ExitThread", "Tcl_Export", "Tcl_ExposeCommand", "Tcl_ExprBoolean", "Tcl_ExprBooleanObj",
  1375. "Tcl_ExprDouble", "Tcl_ExprDoubleObj", "Tcl_ExprLong", "Tcl_ExprLongObj", "Tcl_ExprObj", "Tcl_ExprString",
  1376. "Tcl_ExternalToUtf", "Tcl_ExternalToUtfDString", "Tcl_Finalize", "Tcl_FinalizeNotifier",
  1377. "Tcl_FinalizeThread", "Tcl_FindCommand", "Tcl_FindEnsemble", "Tcl_FindExecutable", "Tcl_FindHashEntry",
  1378. "Tcl_FindNamespace", "Tcl_FirstHashEntry", "Tcl_Flush", "Tcl_ForgetImport", "Tcl_Format",
  1379. "Tcl_Free· Tcl_FreeEncoding", "Tcl_FreeParse", "Tcl_FreeResult", "Tcl_FSAccess", "Tcl_FSChdir",
  1380. "Tcl_FSConvertToPathType", "Tcl_FSCopyDirectory", "Tcl_FSCopyFile", "Tcl_FSCreateDirectory", "Tcl_FSData",
  1381. "Tcl_FSDeleteFile", "Tcl_FSEqualPaths", "Tcl_FSEvalFile", "Tcl_FSEvalFileEx", "Tcl_FSFileAttrsGet",
  1382. "Tcl_FSFileAttrsSet", "Tcl_FSFileAttrStrings", "Tcl_FSFileSystemInfo", "Tcl_FSGetCwd",
  1383. "Tcl_FSGetFileSystemForPath", "Tcl_FSGetInternalRep", "Tcl_FSGetNativePath", "Tcl_FSGetNormalizedPath",
  1384. "Tcl_FSGetPathType", "Tcl_FSGetTranslatedPath", "Tcl_FSGetTranslatedStringPath", "Tcl_FSJoinPath",
  1385. "Tcl_FSJoinToPath", "Tcl_FSLink· Tcl_FSListVolumes", "Tcl_FSLoadFile", "Tcl_FSLstat",
  1386. "Tcl_FSMatchInDirectory", "Tcl_FSMountsChanged", "Tcl_FSNewNativePath", "Tcl_FSOpenFileChannel",
  1387. "Tcl_FSPathSeparator", "Tcl_FSRegister", "Tcl_FSRemoveDirectory", "Tcl_FSRenameFile", "Tcl_FSSplitPath",
  1388. "Tcl_FSStat", "Tcl_FSUnloadFile", "Tcl_FSUnregister", "Tcl_FSUtime", "Tcl_GetAccessTimeFromStat",
  1389. "Tcl_GetAlias", "Tcl_GetAliasObj", "Tcl_GetAssocData", "Tcl_GetBignumFromObj", "Tcl_GetBlocksFromStat",
  1390. "Tcl_GetBlockSizeFromStat", "Tcl_GetBoolean", "Tcl_GetBooleanFromObj", "Tcl_GetByteArrayFromObj",
  1391. "Tcl_GetChangeTimeFromStat", "Tcl_GetChannel", "Tcl_GetChannelBufferSize", "Tcl_GetChannelError",
  1392. "Tcl_GetChannelErrorInterp", "Tcl_GetChannelHandle", "Tcl_GetChannelInstanceData", "Tcl_GetChannelMode",
  1393. "Tcl_GetChannelName", "Tcl_GetChannelNames", "Tcl_GetChannelNamesEx", "Tcl_GetChannelOption",
  1394. "Tcl_GetChannelThread", "Tcl_GetChannelType", "Tcl_GetCharLength", "Tcl_GetClassAsObject",
  1395. "Tcl_GetCommandFromObj", "Tcl_GetCommandFullName", "Tcl_GetCommandInfo", "Tcl_GetCommandInfoFromToken",
  1396. "Tcl_GetCommandName", "Tcl_GetCurrentNamespace", "Tcl_GetCurrentThread", "Tcl_GetCwd",
  1397. "Tcl_GetDefaultEncodingDir", "Tcl_GetDeviceTypeFromStat", "Tcl_GetDouble", "Tcl_GetDoubleFromObj",
  1398. "Tcl_GetEncoding", "Tcl_GetEncodingFromObj", "Tcl_GetEncodingName", "Tcl_GetEncodingNameFromEnvironment",
  1399. "Tcl_GetEncodingNames", "Tcl_GetEncodingSearchPath", "Tcl_GetEnsembleFlags", "Tcl_GetEnsembleMappingDict",
  1400. "Tcl_GetEnsembleNamespace", "Tcl_GetEnsembleParameterList", "Tcl_GetEnsembleSubcommandList",
  1401. "Tcl_GetEnsembleUnknownHandler", "Tcl_GetErrno", "Tcl_GetErrorLine", "Tcl_GetFSDeviceFromStat",
  1402. "Tcl_GetFSInodeFromStat", "Tcl_GetGlobalNamespace", "Tcl_GetGroupIdFromStat", "Tcl_GetHashKey",
  1403. "Tcl_GetHashValue", "Tcl_GetHostName", "Tcl_GetIndexFromObj", "Tcl_GetIndexFromObjStruct", "Tcl_GetInt",
  1404. "Tcl_GetInterpPath", "Tcl_GetIntFromObj", "Tcl_GetLinkCountFromStat", "Tcl_GetLongFromObj", "Tcl_GetMaster",
  1405. "Tcl_GetMathFuncInfo", "Tcl_GetModeFromStat", "Tcl_GetModificationTimeFromStat", "Tcl_GetNameOfExecutable",
  1406. "Tcl_GetNamespaceUnknownHandler", "Tcl_GetObjectAsClass", "Tcl_GetObjectCommand", "Tcl_GetObjectFromObj",
  1407. "Tcl_GetObjectName", "Tcl_GetObjectNamespace", "Tcl_GetObjResult", "Tcl_GetObjType", "Tcl_GetOpenFile",
  1408. "Tcl_GetPathType", "Tcl_GetRange", "Tcl_GetRegExpFromObj", "Tcl_GetReturnOptions", "Tcl_Gets",
  1409. "Tcl_GetServiceMode", "Tcl_GetSizeFromStat", "Tcl_GetSlave", "Tcl_GetsObj", "Tcl_GetStackedChannel",
  1410. "Tcl_GetStartupScript", "Tcl_GetStdChannel", "Tcl_GetString", "Tcl_GetStringFromObj", "Tcl_GetStringResult",
  1411. "Tcl_GetThreadData", "Tcl_GetTime", "Tcl_GetTopChannel", "Tcl_GetUniChar", "Tcl_GetUnicode",
  1412. "Tcl_GetUnicodeFromObj", "Tcl_GetUserIdFromStat", "Tcl_GetVar", "Tcl_GetVar2", "Tcl_GetVar2Ex",
  1413. "Tcl_GetVersion", "Tcl_GetWideIntFromObj", "Tcl_GlobalEval", "Tcl_GlobalEvalObj", "Tcl_HashStats",
  1414. "Tcl_HideCommand", "Tcl_Import", "Tcl_IncrRefCount", "Tcl_Init", "Tcl_InitCustomHashTable",
  1415. "Tcl_InitHashTable", "Tcl_InitMemory", "Tcl_InitNotifier", "Tcl_InitObjHashTable", "Tcl_InitStubs",
  1416. "Tcl_InputBlocked", "Tcl_InputBuffered", "Tcl_InterpActive", "Tcl_InterpDeleted", "Tcl_InvalidateStringRep",
  1417. "Tcl_IsChannelExisting", "Tcl_IsChannelRegistered", "Tcl_IsChannelShared", "Tcl_IsEnsemble", "Tcl_IsSafe",
  1418. "Tcl_IsShared", "Tcl_IsStandardChannel", "Tcl_JoinPath", "Tcl_JoinThread", "Tcl_LimitAddHandler",
  1419. "Tcl_LimitCheck", "Tcl_LimitExceeded", "Tcl_LimitGetCommands", "Tcl_LimitGetGranularity",
  1420. "Tcl_LimitGetTime", "Tcl_LimitReady", "Tcl_LimitRemoveHandler", "Tcl_LimitSetCommands",
  1421. "Tcl_LimitSetGranularity", "Tcl_LimitSetTime", "Tcl_LimitTypeEnabled", "Tcl_LimitTypeExceeded",
  1422. "Tcl_LimitTypeReset", "Tcl_LimitTypeSet", "Tcl_LinkVar", "Tcl_ListMathFuncs", "Tcl_ListObjAppendElement",
  1423. "Tcl_ListObjAppendList", "Tcl_ListObjGetElements", "Tcl_ListObjIndex", "Tcl_ListObjLength",
  1424. "Tcl_ListObjReplace", "Tcl_LogCommandInfo", "Tcl_Main", "Tcl_MakeFileChannel", "Tcl_MakeSafe",
  1425. "Tcl_MakeTcpClientChannel", "Tcl_Merge", "Tcl_MethodDeclarerClass", "Tcl_MethodDeclarerObject",
  1426. "Tcl_MethodIsPublic", "Tcl_MethodIsType", "Tcl_MethodName", "Tcl_MutexFinalize", "Tcl_MutexLock",
  1427. "Tcl_MutexUnlock", "Tcl_NewBignumObj", "Tcl_NewBooleanObj", "Tcl_NewByteArrayObj", "Tcl_NewDictObj",
  1428. "Tcl_NewDoubleObj", "Tcl_NewInstanceMethod", "Tcl_NewIntObj", "Tcl_NewListObj", "Tcl_NewLongObj",
  1429. "Tcl_NewMethod", "Tcl_NewObj", "Tcl_NewObjectInstance", "Tcl_NewStringObj", "Tcl_NewUnicodeObj",
  1430. "Tcl_NewWideIntObj", "Tcl_NextHashEntry", "Tcl_NotifyChannel", "Tcl_NRAddCallback", "Tcl_NRCallObjProc",
  1431. "Tcl_NRCmdSwap", "Tcl_NRCreateCommand", "Tcl_NREvalObj", "Tcl_NREvalObjv", "Tcl_NumUtfChars",
  1432. "Tcl_ObjectContextInvokeNext", "Tcl_ObjectContextIsFiltering", "Tcl_ObjectContextMethod",
  1433. "Tcl_ObjectContextObject", "Tcl_ObjectContextSkippedArgs", "Tcl_ObjectDeleted", "Tcl_ObjectGetMetadata",
  1434. "Tcl_ObjectGetMethodNameMapper", "Tcl_ObjectSetMetadata", "Tcl_ObjectSetMethodNameMapper", "Tcl_ObjGetVar2",
  1435. "Tcl_ObjPrintf", "Tcl_ObjSetVar2", "Tcl_OpenCommandChannel", "Tcl_OpenFileChannel", "Tcl_OpenTcpClient",
  1436. "Tcl_OpenTcpServer", "Tcl_OutputBuffered", "Tcl_Panic", "Tcl_PanicVA", "Tcl_ParseArgsObjv",
  1437. "Tcl_ParseBraces", "Tcl_ParseCommand", "Tcl_ParseExpr", "Tcl_ParseQuotedString", "Tcl_ParseVar",
  1438. "Tcl_ParseVarName", "Tcl_PkgPresent", "Tcl_PkgPresentEx", "Tcl_PkgProvide", "Tcl_PkgProvideEx",
  1439. "Tcl_PkgRequire", "Tcl_PkgRequireEx", "Tcl_PkgRequireProc", "Tcl_PosixError", "Tcl_Preserve",
  1440. "Tcl_PrintDouble", "Tcl_PutEnv", "Tcl_QueryTimeProc", "Tcl_QueueEvent", "Tcl_Read", "Tcl_ReadChars",
  1441. "Tcl_ReadRaw", "Tcl_Realloc", "Tcl_ReapDetachedProcs", "Tcl_RecordAndEval", "Tcl_RecordAndEvalObj",
  1442. "Tcl_RegExpCompile", "Tcl_RegExpExec", "Tcl_RegExpExecObj", "Tcl_RegExpGetInfo", "Tcl_RegExpMatch",
  1443. "Tcl_RegExpMatchObj", "Tcl_RegExpRange", "Tcl_RegisterChannel", "Tcl_RegisterConfig", "Tcl_RegisterObjType",
  1444. "Tcl_Release", "Tcl_ResetResult", "Tcl_RestoreInterpState", "Tcl_RestoreResult", "Tcl_SaveInterpState",
  1445. "Tcl_SaveResult", "Tcl_ScanCountedElement", "Tcl_ScanElement", "Tcl_Seek", "Tcl_ServiceAll",
  1446. "Tcl_ServiceEvent", "Tcl_ServiceModeHook", "Tcl_SetAssocData", "Tcl_SetBignumObj", "Tcl_SetBooleanObj",
  1447. "Tcl_SetByteArrayLength", "Tcl_SetByteArrayObj", "Tcl_SetChannelBufferSize", "Tcl_SetChannelError",
  1448. "Tcl_SetChannelErrorInterp", "Tcl_SetChannelOption", "Tcl_SetCommandInfo", "Tcl_SetCommandInfoFromToken",
  1449. "Tcl_SetDefaultEncodingDir", "Tcl_SetDoubleObj", "Tcl_SetEncodingSearchPath", "Tcl_SetEnsembleFlags",
  1450. "Tcl_SetEnsembleMappingDict", "Tcl_SetEnsembleParameterList", "Tcl_SetEnsembleSubcommandList",
  1451. "Tcl_SetEnsembleUnknownHandler", "Tcl_SetErrno", "Tcl_SetErrorCode", "Tcl_SetErrorCodeVA",
  1452. "Tcl_SetErrorLine", "Tcl_SetExitProc", "Tcl_SetHashValue", "Tcl_SetIntObj", "Tcl_SetListObj",
  1453. "Tcl_SetLongObj", "Tcl_SetMainLoop", "Tcl_SetMaxBlockTime", "Tcl_SetNamespaceUnknownHandler",
  1454. "Tcl_SetNotifier", "Tcl_SetObjErrorCode", "Tcl_SetObjLength", "Tcl_SetObjResult", "Tcl_SetPanicProc",
  1455. "Tcl_SetRecursionLimit", "Tcl_SetResult", "Tcl_SetReturnOptions", "Tcl_SetServiceMode",
  1456. "Tcl_SetStartupScript", "Tcl_SetStdChannel", "Tcl_SetStringObj", "Tcl_SetSystemEncoding", "Tcl_SetTimeProc",
  1457. "Tcl_SetTimer", "Tcl_SetUnicodeObj", "Tcl_SetVar", "Tcl_SetVar2", "Tcl_SetVar2Ex", "Tcl_SetWideIntObj",
  1458. "Tcl_SignalId", "Tcl_SignalMsg", "Tcl_Sleep", "Tcl_SourceRCFile", "Tcl_SpliceChannel", "Tcl_SplitList",
  1459. "Tcl_SplitPath", "Tcl_StackChannel", "Tcl_StandardChannels", "Tcl_Stat", "Tcl_StaticPackage",
  1460. "Tcl_StringCaseMatch", "Tcl_StringMatch", "Tcl_SubstObj", "Tcl_TakeBignumFromObj", "Tcl_Tell",
  1461. "Tcl_ThreadAlert", "Tcl_ThreadQueueEvent", "Tcl_TraceCommand", "Tcl_TraceVar", "Tcl_TraceVar2",
  1462. "Tcl_TransferResult", "Tcl_TranslateFileName", "Tcl_TruncateChannel", "Tcl_Ungets", "Tcl_UniChar",
  1463. "Tcl_UniCharAtIndex", "Tcl_UniCharCaseMatch", "Tcl_UniCharIsAlnum", "Tcl_UniCharIsAlpha",
  1464. "Tcl_UniCharIsControl", "Tcl_UniCharIsDigit", "Tcl_UniCharIsGraph", "Tcl_UniCharIsLower",
  1465. "Tcl_UniCharIsPrint", "Tcl_UniCharIsPunct", "Tcl_UniCharIsSpace", "Tcl_UniCharIsUpper",
  1466. "Tcl_UniCharIsWordChar", "Tcl_UniCharLen", "Tcl_UniCharNcasecmp", "Tcl_UniCharNcmp", "Tcl_UniCharToLower",
  1467. "Tcl_UniCharToTitle", "Tcl_UniCharToUpper", "Tcl_UniCharToUtf", "Tcl_UniCharToUtfDString", "Tcl_UnlinkVar",
  1468. "Tcl_UnregisterChannel", "Tcl_UnsetVar", "Tcl_UnsetVar2", "Tcl_UnstackChannel", "Tcl_UntraceCommand",
  1469. "Tcl_UntraceVar", "Tcl_UntraceVar2", "Tcl_UpdateLinkedVar", "Tcl_UpVar", "Tcl_UpVar2", "Tcl_UtfAtIndex",
  1470. "Tcl_UtfBackslash", "Tcl_UtfCharComplete", "Tcl_UtfFindFirst", "Tcl_UtfFindLast", "Tcl_UtfNext",
  1471. "Tcl_UtfPrev", "Tcl_UtfToExternal", "Tcl_UtfToExternalDString", "Tcl_UtfToLower", "Tcl_UtfToTitle",
  1472. "Tcl_UtfToUniChar", "Tcl_UtfToUniCharDString", "Tcl_UtfToUpper", "Tcl_ValidateAllMemory", "Tcl_VarEval",
  1473. "Tcl_VarEvalVA", "Tcl_VarTraceInfo", "Tcl_VarTraceInfo2", "Tcl_WaitForEvent", "Tcl_WaitPid",
  1474. "Tcl_WinTCharToUtf", "Tcl_WinUtfToTChar", "Tcl_Write", "Tcl_WriteChars", "Tcl_WriteObj", "Tcl_WriteRaw",
  1475. "Tcl_WrongNumArgs", "Tcl_ZlibAdler32", "Tcl_ZlibCRC32", "Tcl_ZlibDeflate", "Tcl_ZlibInflate",
  1476. "Tcl_ZlibStreamChecksum", "Tcl_ZlibStreamClose", "Tcl_ZlibStreamEof", "Tcl_ZlibStreamGet",
  1477. "Tcl_ZlibStreamGetCommandName", "Tcl_ZlibStreamInit", "Tcl_ZlibStreamPut", "dde", "http", "msgcat",
  1478. "registry", "tcltest", "Tcl_AllocHashEntryProc", "Tcl_AppInitProc", "Tcl_ArgvInfo", "Tcl_AsyncProc",
  1479. "Tcl_ChannelProc", "Tcl_ChannelType", "Tcl_CloneProc", "Tcl_CloseProc", "Tcl_CmdDeleteProc", "Tcl_CmdInfo",
  1480. "Tcl_CmdObjTraceDeleteProc", "Tcl_CmdObjTraceProc", "Tcl_CmdProc", "Tcl_CmdTraceProc",
  1481. "Tcl_CommandTraceProc", "Tcl_CompareHashKeysProc", "Tcl_Config", "Tcl_DriverBlockModeProc",
  1482. "Tcl_DriverClose2Proc", "Tcl_DriverCloseProc", "Tcl_DriverFlushProc", "Tcl_DriverGetHandleProc",
  1483. "Tcl_DriverGetOptionProc", "Tcl_DriverHandlerProc", "Tcl_DriverInputProc", "Tcl_DriverOutputProc",
  1484. "Tcl_DriverSeekProc", "Tcl_DriverSetOptionProc", "Tcl_DriverThreadActionProc", "Tcl_DriverTruncateProc",
  1485. "Tcl_DriverWatchProc", "Tcl_DriverWideSeekProc", "Tcl_DupInternalRepProc", "Tcl_EncodingConvertProc",
  1486. "Tcl_EncodingFreeProc", "Tcl_EncodingType", "Tcl_Event", "Tcl_EventCheckProc", "Tcl_EventDeleteProc",
  1487. "Tcl_EventProc", "Tcl_EventSetupProc", "Tcl_ExitProc", "Tcl_FileProc", "Tcl_Filesystem",
  1488. "Tcl_FreeHashEntryProc", "Tcl_FreeInternalRepProc", "Tcl_FreeProc", "Tcl_FSAccessProc", "Tcl_FSChdirProc",
  1489. "Tcl_FSCopyDirectoryProc", "Tcl_FSCopyFileProc", "Tcl_FSCreateDirectoryProc", "Tcl_FSCreateInternalRepProc",
  1490. "Tcl_FSDeleteFileProc", "Tcl_FSDupInternalRepProc", "Tcl_FSFileAttrsGetProc", "Tcl_FSFileAttrsSetProc",
  1491. "Tcl_FSFilesystemPathTypeProc", "Tcl_FSFilesystemSeparatorProc", "Tcl_FSFreeInternalRepProc",
  1492. "Tcl_FSGetCwdProc", "Tcl_FSInternalToNormalizedProc", "Tcl_FSLinkProc", "Tcl_FSListVolumesProc",
  1493. "Tcl_FSLoadFileProc", "Tcl_FSLstatProc", "Tcl_FSMatchInDirectoryProc", "Tcl_FSNormalizePathProc",
  1494. "Tcl_FSOpenFileChannelProc", "Tcl_FSPathInFilesystemProc", "Tcl_FSRemoveDirectoryProc",
  1495. "Tcl_FSRenameFileProc", "Tcl_FSStatProc", "Tcl_FSUnloadFileProc", "Tcl_FSUtimeProc", "Tcl_GlobTypeData",
  1496. "Tcl_HashKeyType", "Tcl_IdleProc", "Tcl_Interp", "Tcl_InterpDeleteProc", "Tcl_LimitHandlerDeleteProc",
  1497. "Tcl_LimitHandlerProc", "Tcl_MainLoopProc", "Tcl_MathProc", "Tcl_MethodCallProc", "Tcl_MethodDeleteProc",
  1498. "Tcl_MethodType", "Tcl_NamespaceDeleteProc", "Tcl_NotifierProcs", "Tcl_Obj", "Tcl_ObjCmdProc",
  1499. "Tcl_ObjectMapMethodNameProc", "Tcl_ObjectMetadataDeleteProc", "Tcl_ObjType", "Tcl_PackageInitProc",
  1500. "Tcl_PackageUnloadProc", "Tcl_PanicProc", "Tcl_RegExpIndices", "Tcl_RegExpInfo", "Tcl_ScaleTimeProc",
  1501. "Tcl_SetFromAnyProc", "Tcl_TcpAcceptProc", "Tcl_Time", "Tcl_TimerProc", "Tcl_Token", "Tcl_UpdateStringProc",
  1502. "Tcl_Value", "Tcl_VarTraceProc", "argc", "argv", "argv0", "auto_path", "env", "errorCode", "errorInfo",
  1503. "filename", "re_syntax", "safe", "Tcl", "tcl_interactive", "tcl_library", "TCL_MEM_DEBUG",
  1504. "tcl_nonwordchars", "tcl_patchLevel", "tcl_pkgPath", "tcl_platform", "tcl_precision", "tcl_rcFileName",
  1505. "tcl_traceCompile", "tcl_traceEval", "tcl_version", "tcl_wordchars"
  1506. ]
  1507. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords + self.tcl_keywords
  1508. self.shell = FCShell(self, version=self.version)
  1509. self.shell._edit.set_model_data(self.myKeywords)
  1510. self.ui.code_editor.set_model_data(self.myKeywords)
  1511. self.shell.setWindowIcon(self.ui.app_icon)
  1512. self.shell.setWindowTitle("FlatCAM Shell")
  1513. self.shell.resize(*self.defaults["global_shell_shape"])
  1514. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1515. self.shell.append_output("(Type help to get started)\n\n")
  1516. self.init_tcl()
  1517. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1518. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1519. self.ui.shell_dock.setWidget(self.shell)
  1520. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1521. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1522. QtWidgets.QDockWidget.DockWidgetFloatable |
  1523. QtWidgets.QDockWidget.DockWidgetClosable)
  1524. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1525. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1526. if self.defaults["global_shell_at_startup"]:
  1527. self.ui.shell_dock.show()
  1528. else:
  1529. self.ui.shell_dock.hide()
  1530. #########################
  1531. ### Tools and Plugins ###
  1532. #########################
  1533. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1534. self.install_tools()
  1535. ### System Font Parsing ###
  1536. # self.f_parse = ParseFont(self)
  1537. # self.parse_system_fonts()
  1538. # test if the program was started with a script as parameter
  1539. if self.cmd_line_shellfile:
  1540. try:
  1541. with open(self.cmd_line_shellfile, "r") as myfile:
  1542. cmd_line_shellfile_text = myfile.read()
  1543. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1544. except Exception as ext:
  1545. print("ERROR: ", ext)
  1546. sys.exit(2)
  1547. ###########################
  1548. #### Check for updates ####
  1549. ###########################
  1550. # Separate thread (Not worker)
  1551. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1552. if (self.beta is False or self.beta is None) and \
  1553. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1554. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1555. self.thr2 = QtCore.QThread()
  1556. self.worker_task.emit({'fcn': self.version_check,
  1557. 'params': []})
  1558. self.thr2.start(QtCore.QThread.LowPriority)
  1559. ####################################
  1560. #### Variables for global usage ####
  1561. ####################################
  1562. # coordinates for relative position display
  1563. self.rel_point1 = (0, 0)
  1564. self.rel_point2 = (0, 0)
  1565. # variable to store coordinates
  1566. self.pos = (0, 0)
  1567. self.pos_jump = (0, 0)
  1568. # decide if we have a double click or single click
  1569. self.doubleclick = False
  1570. # variable to store if a command is active (then the var is not None) and which one it is
  1571. self.command_active = None
  1572. # variable to store the status of moving selection action
  1573. # None value means that it's not an selection action
  1574. # True value = a selection from left to right
  1575. # False value = a selection from right to left
  1576. self.selection_type = None
  1577. # List to store the objects that are currently loaded in FlatCAM
  1578. # This list is updated on each object creation or object delete
  1579. self.all_objects_list = []
  1580. # List to store the objects that are selected
  1581. self.sel_objects_list = []
  1582. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1583. self.key_modifiers = None
  1584. # Variable to hold the status of the axis
  1585. self.toggle_axis = True
  1586. # Variable to store the status of the fullscreen event
  1587. self.toggle_fscreen = False
  1588. # Variable to store the status of the code editor
  1589. self.toggle_codeeditor = False
  1590. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1591. self.click_noproject = False
  1592. self.cursor = None
  1593. # Variable to store the GCODE that was edited
  1594. self.gcode_edited = ""
  1595. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3',
  1596. 'gko', 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15',
  1597. 'dim', 'mil', 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo',
  1598. 'art', 'gbd', 'gb0', 'gb1', 'gb2', 'gb3', 'g4', 'gb5', 'gb6', 'gb7', 'gb8', 'gb9'
  1599. ]
  1600. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc']
  1601. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1602. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1603. 'mpf']
  1604. self.svg_list = ['svg']
  1605. self.dxf_list = ['dxf']
  1606. self.pdf_list = ['pdf']
  1607. self.prj_list = ['flatprj']
  1608. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1609. # flag for polygons not cleared
  1610. self.poly_not_cleared = False
  1611. # VisPy visuals
  1612. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.vispy_canvas.view.scene, layers=1)
  1613. self.isHovering = False
  1614. self.notHovering = True
  1615. ### Save defaults to factory_defaults.FlatConfig file ###
  1616. ### It's done only once after install #############
  1617. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1618. fac_def_from_file = factory_file.read()
  1619. factory_defaults = json.loads(fac_def_from_file)
  1620. # if the file contain an empty dictionary then save the factory defaults into the file
  1621. if not factory_defaults:
  1622. self.save_factory_defaults(silent=False)
  1623. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1624. initial_lay = 'compact'
  1625. self.on_layout(lay=initial_lay)
  1626. # Set the combobox in Preferences to the current layout
  1627. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  1628. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  1629. factory_file.close()
  1630. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1631. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1632. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1633. # Post-GUI initialization: Experimental attempt
  1634. # to perform unit tests on the GUI.
  1635. # if post_gui is not None:
  1636. # post_gui(self)
  1637. App.log.debug("END of constructor. Releasing control.")
  1638. # accept a project file as command line parameter
  1639. # the path/file_name must be enclosed in quotes if it contain spaces
  1640. for argument in App.args:
  1641. if '.FlatPrj' in argument:
  1642. try:
  1643. project_name = str(argument)
  1644. if project_name == "":
  1645. self.inform.emit(_("Open cancelled."))
  1646. else:
  1647. # self.open_project(project_name)
  1648. run_from_arg = True
  1649. self.worker_task.emit({'fcn': self.open_project,
  1650. 'params': [project_name, run_from_arg]})
  1651. except Exception as e:
  1652. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1653. if '.FlatConfig' in argument:
  1654. try:
  1655. file_name = str(argument)
  1656. if file_name == "":
  1657. self.inform.emit(_("Open Config file failed."))
  1658. else:
  1659. # run_from_arg = True
  1660. # self.worker_task.emit({'fcn': self.open_config_file,
  1661. # 'params': [file_name, run_from_arg]})
  1662. self.open_config_file(file_name, run_from_arg=True)
  1663. except Exception as e:
  1664. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1665. if '.FlatScript' in argument:
  1666. try:
  1667. file_name = str(argument)
  1668. if file_name == "":
  1669. self.inform.emit(_("Open Script file failed."))
  1670. else:
  1671. # run_from_arg = True
  1672. # self.worker_task.emit({'fcn': self.open_script_file,
  1673. # 'params': [file_name, run_from_arg]})
  1674. self.on_filerunscript(name=file_name)
  1675. except Exception as e:
  1676. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1677. def defaults_read_form(self):
  1678. for option in self.defaults_form_fields:
  1679. try:
  1680. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1681. except:
  1682. pass
  1683. def defaults_write_form(self, factor=None):
  1684. for option in self.defaults:
  1685. self.defaults_write_form_field(option, factor=factor)
  1686. # try:
  1687. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1688. # except KeyError:
  1689. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1690. # # TODO: Rethink this?
  1691. # pass
  1692. def defaults_write_form_field(self, field, factor=None):
  1693. try:
  1694. if factor is None:
  1695. self.defaults_form_fields[field].set_value(self.defaults[field])
  1696. else:
  1697. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  1698. except KeyError:
  1699. #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1700. # TODO: Rethink this?
  1701. pass
  1702. except AttributeError:
  1703. log.debug(field)
  1704. def clear_pool(self):
  1705. self.pool.close()
  1706. self.pool = Pool()
  1707. self.pool_recreated.emit(self.pool)
  1708. gc.collect()
  1709. # the order that the tools are installed is important as they can depend on each other install position
  1710. def install_tools(self):
  1711. self.dblsidedtool = DblSidedTool(self)
  1712. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1713. self.measurement_tool = Measurement(self)
  1714. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1715. self.panelize_tool = Panelize(self)
  1716. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1717. self.film_tool = Film(self)
  1718. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  1719. self.paste_tool = SolderPaste(self)
  1720. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  1721. self.calculator_tool = ToolCalculator(self)
  1722. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
  1723. self.sub_tool = ToolSub(self)
  1724. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menuedit_convert,
  1725. before=self.ui.menuedit_convert_sg2mg)
  1726. self.move_tool = ToolMove(self)
  1727. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1728. before=self.ui.menueditorigin)
  1729. self.cutout_tool = CutOut(self)
  1730. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  1731. before=self.measurement_tool.menuAction)
  1732. self.ncclear_tool = NonCopperClear(self)
  1733. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  1734. before=self.measurement_tool.menuAction, separator=True)
  1735. self.paint_tool = ToolPaint(self)
  1736. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1737. before=self.measurement_tool.menuAction, separator=True)
  1738. self.transform_tool = ToolTransform(self)
  1739. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1740. self.properties_tool = Properties(self)
  1741. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1742. self.pdf_tool = ToolPDF(self)
  1743. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  1744. separator=True)
  1745. self.image_tool = ToolImage(self)
  1746. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1747. separator=True)
  1748. self.pcb_wizard_tool = PcbWizard(self)
  1749. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  1750. self.log.debug("Tools are installed.")
  1751. def remove_tools(self):
  1752. for act in self.ui.menutool.actions():
  1753. self.ui.menutool.removeAction(act)
  1754. def init_tools(self):
  1755. log.debug("init_tools()")
  1756. # delete the data currently in the Tools Tab and the Tab itself
  1757. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1758. if widget is not None:
  1759. widget.deleteLater()
  1760. self.ui.notebook.removeTab(2)
  1761. # rebuild the Tools Tab
  1762. self.ui.tool_tab = QtWidgets.QWidget()
  1763. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1764. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1765. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1766. self.ui.tool_scroll_area = VerticalScrollArea()
  1767. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1768. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1769. # first remove all of them
  1770. self.remove_tools()
  1771. # second re add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1772. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  1773. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1774. # third install all of them
  1775. self.install_tools()
  1776. self.log.debug("Tools are initialized.")
  1777. # def parse_system_fonts(self):
  1778. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1779. # 'params': []})
  1780. def connect_toolbar_signals(self):
  1781. # Toolbar
  1782. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1783. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1784. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1785. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1786. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1787. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1788. self.ui.replot_btn.triggered.connect(self.plot_all)
  1789. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1790. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1791. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1792. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1793. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1794. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1795. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1796. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1797. self.ui.delete_btn.triggered.connect(self.on_delete)
  1798. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  1799. # Tools Toolbar Signals
  1800. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1801. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1802. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1803. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1804. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1805. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1806. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1807. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1808. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1809. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1810. def object2editor(self):
  1811. """
  1812. Send the current Geometry or Excellon object (if any) into the editor.
  1813. :return: None
  1814. """
  1815. self.report_usage("object2editor()")
  1816. edited_object = self.collection.get_active()
  1817. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  1818. isinstance(edited_object, FlatCAMExcellon):
  1819. pass
  1820. else:
  1821. self.inform.emit(_("[WARNING_NOTCL] Select a Geometry, Gerber or Excellon Object to edit."))
  1822. return
  1823. if isinstance(edited_object, FlatCAMGeometry):
  1824. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1825. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1826. if edited_object.multigeo is True:
  1827. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  1828. if len(edited_tools) > 1:
  1829. self.inform.emit(_("[WARNING_NOTCL] Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  1830. "is not possible.\n"
  1831. "Edit only one geometry at a time."))
  1832. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=edited_tools[0])
  1833. else:
  1834. self.geo_editor.edit_fcgeometry(edited_object)
  1835. # we set the notebook to hidden
  1836. self.ui.splitter.setSizes([0, 1])
  1837. # set call source to the Editor we go into
  1838. self.call_source = 'geo_editor'
  1839. elif isinstance(edited_object, FlatCAMExcellon):
  1840. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1841. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1842. self.exc_editor.edit_fcexcellon(edited_object)
  1843. # set call source to the Editor we go into
  1844. self.call_source = 'exc_editor'
  1845. if self.ui.splitter.sizes()[0] == 0:
  1846. self.ui.splitter.setSizes([1, 1])
  1847. elif isinstance(edited_object, FlatCAMGerber):
  1848. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1849. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1850. self.grb_editor.edit_fcgerber(edited_object)
  1851. # set call source to the Editor we go into
  1852. self.call_source = 'grb_editor'
  1853. if self.ui.splitter.sizes()[0] == 0:
  1854. self.ui.splitter.setSizes([1, 1])
  1855. # # make sure that we can't select another object while in Editor Mode:
  1856. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1857. self.ui.project_frame.setDisabled(True)
  1858. # delete any selection shape that might be active as they are not relevant in Editor
  1859. self.delete_selection_shape()
  1860. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1861. self.ui.plot_tab_area.protectTab(0)
  1862. self.inform.emit(_("[WARNING_NOTCL] Editor is activated ..."))
  1863. self.should_we_save = True
  1864. def editor2object(self, cleanup=None):
  1865. """
  1866. Transfers the Geometry or Excellon from the editor to the current object.
  1867. :return: None
  1868. """
  1869. self.report_usage("editor2object()")
  1870. # do not update a geometry or excellon object unless it comes out of an editor
  1871. if self.call_source != 'app':
  1872. edited_obj = self.collection.get_active()
  1873. obj_type = ""
  1874. if cleanup is None:
  1875. msgbox = QtWidgets.QMessageBox()
  1876. msgbox.setText(_("Do you want to save the edited object?"))
  1877. msgbox.setWindowTitle(_("Close Editor"))
  1878. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  1879. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1880. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1881. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1882. msgbox.setDefaultButton(bt_yes)
  1883. msgbox.exec_()
  1884. response = msgbox.clickedButton()
  1885. if response == bt_yes:
  1886. # clean the Tools Tab
  1887. self.ui.tool_scroll_area.takeWidget()
  1888. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1889. self.ui.notebook.setTabText(2, "Tool")
  1890. if isinstance(edited_obj, FlatCAMGeometry):
  1891. obj_type = "Geometry"
  1892. if cleanup is None:
  1893. self.geo_editor.update_fcgeometry(edited_obj)
  1894. self.geo_editor.update_options(edited_obj)
  1895. self.geo_editor.deactivate()
  1896. # update the geo object options so it is including the bounding box values
  1897. try:
  1898. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1899. edited_obj.options['xmin'] = xmin
  1900. edited_obj.options['ymin'] = ymin
  1901. edited_obj.options['xmax'] = xmax
  1902. edited_obj.options['ymax'] = ymax
  1903. except AttributeError as e:
  1904. self.inform.emit(_("[WARNING] Object empty after edit."))
  1905. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1906. elif isinstance(edited_obj, FlatCAMGerber):
  1907. obj_type = "Gerber"
  1908. if cleanup is None:
  1909. self.grb_editor.update_fcgerber(edited_obj)
  1910. self.grb_editor.update_options(edited_obj)
  1911. self.grb_editor.deactivate_grb_editor()
  1912. # delete the old object (the source object) if it was an empty one
  1913. if len(edited_obj.solid_geometry) == 0:
  1914. old_name = edited_obj.options['name']
  1915. self.collection.set_active(old_name)
  1916. self.collection.delete_active()
  1917. elif isinstance(edited_obj, FlatCAMExcellon):
  1918. obj_type = "Excellon"
  1919. if cleanup is None:
  1920. self.exc_editor.update_fcexcellon(edited_obj)
  1921. self.exc_editor.update_options(edited_obj)
  1922. self.exc_editor.deactivate()
  1923. else:
  1924. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  1925. return
  1926. self.inform.emit(_("[selected] %s is updated, returning to App...") % obj_type)
  1927. elif response == bt_no:
  1928. # clean the Tools Tab
  1929. self.ui.tool_scroll_area.takeWidget()
  1930. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1931. self.ui.notebook.setTabText(2, "Tool")
  1932. if isinstance(edited_obj, FlatCAMGeometry):
  1933. self.geo_editor.deactivate()
  1934. elif isinstance(edited_obj, FlatCAMGerber):
  1935. self.grb_editor.deactivate_grb_editor()
  1936. elif isinstance(edited_obj, FlatCAMExcellon):
  1937. self.exc_editor.deactivate()
  1938. # set focus on the project tab
  1939. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  1940. else:
  1941. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  1942. return
  1943. elif response == bt_cancel:
  1944. return
  1945. else:
  1946. if isinstance(edited_obj, FlatCAMGeometry):
  1947. self.geo_editor.deactivate()
  1948. elif isinstance(edited_obj, FlatCAMGerber):
  1949. self.grb_editor.deactivate_grb_editor()
  1950. elif isinstance(edited_obj, FlatCAMExcellon):
  1951. self.exc_editor.deactivate()
  1952. else:
  1953. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  1954. return
  1955. # if notebook is hidden we show it
  1956. if self.ui.splitter.sizes()[0] == 0:
  1957. self.ui.splitter.setSizes([1, 1])
  1958. # restore the call_source to app
  1959. self.call_source = 'app'
  1960. edited_obj.plot()
  1961. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1962. self.ui.plot_tab_area.protectTab(0)
  1963. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1964. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1965. self.ui.project_frame.setDisabled(False)
  1966. def get_last_folder(self):
  1967. return self.defaults["global_last_folder"]
  1968. def get_last_save_folder(self):
  1969. loc = self.defaults["global_last_save_folder"]
  1970. if loc is None:
  1971. loc = self.defaults["global_last_folder"]
  1972. if loc is None:
  1973. loc = os.path.dirname(__file__)
  1974. return loc
  1975. def report_usage(self, resource):
  1976. """
  1977. Increments usage counter for the given resource
  1978. in self.defaults['global_stats'].
  1979. :param resource: Name of the resource.
  1980. :return: None
  1981. """
  1982. if resource in self.defaults['global_stats']:
  1983. self.defaults['global_stats'][resource] += 1
  1984. else:
  1985. self.defaults['global_stats'][resource] = 1
  1986. def init_tcl(self):
  1987. if hasattr(self,'tcl'):
  1988. # self.tcl = None
  1989. # TODO we need to clean non default variables and procedures here
  1990. # new object cannot be used here as it will not remember values created for next passes,
  1991. # because tcl was execudted in old instance of TCL
  1992. pass
  1993. else:
  1994. self.tcl = tk.Tcl()
  1995. self.setup_shell()
  1996. self.log.debug("TCL Shell has been initialized.")
  1997. # TODO: This shouldn't be here.
  1998. class TclErrorException(Exception):
  1999. """
  2000. this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command
  2001. """
  2002. pass
  2003. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2004. """
  2005. Shows a message on the FlatCAM Shell
  2006. :param msg: Message to display.
  2007. :param show: Opens the shell.
  2008. :param error: Shows the message as an error.
  2009. :return: None
  2010. """
  2011. if show:
  2012. self.ui.shell_dock.show()
  2013. try:
  2014. if error:
  2015. self.shell.append_error(msg + "\n")
  2016. elif warning:
  2017. self.shell.append_warning(msg + "\n")
  2018. elif success:
  2019. self.shell.append_success(msg + "\n")
  2020. elif selected:
  2021. self.shell.append_selected(msg + "\n")
  2022. else:
  2023. self.shell.append_output(msg + "\n")
  2024. except AttributeError:
  2025. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2026. def raise_tcl_unknown_error(self, unknownException):
  2027. """
  2028. Raise exception if is different type than TclErrorException
  2029. this is here mainly to show unknown errors inside TCL shell console.
  2030. :param unknownException:
  2031. :return:
  2032. """
  2033. if not isinstance(unknownException, self.TclErrorException):
  2034. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2035. else:
  2036. raise unknownException
  2037. def display_tcl_error(self, error, error_info=None):
  2038. """
  2039. escape bracket [ with \ otherwise there is error
  2040. "ERROR: missing close-bracket" instead of real error
  2041. :param error: it may be text or exception
  2042. :return: None
  2043. """
  2044. if isinstance(error, Exception):
  2045. exc_type, exc_value, exc_traceback = error_info
  2046. if not isinstance(error, self.TclErrorException):
  2047. show_trace = 1
  2048. else:
  2049. show_trace = int(self.defaults['global_verbose_error_level'])
  2050. if show_trace > 0:
  2051. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2052. trc_formated = []
  2053. for a in reversed(trc):
  2054. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2055. text = "%s\nPython traceback: %s\n%s" % (exc_value,
  2056. exc_type,
  2057. "\n".join(trc_formated))
  2058. else:
  2059. text = "%s" % error
  2060. else:
  2061. text = error
  2062. text = text.replace('[', '\\[').replace('"', '\\"')
  2063. self.tcl.eval('return -code error "%s"' % text)
  2064. def raise_tcl_error(self, text):
  2065. """
  2066. this method pass exception from python into TCL as error, so we get stacktrace and reason
  2067. :param text: text of error
  2068. :return: raise exception
  2069. """
  2070. self.display_tcl_error(text)
  2071. raise self.TclErrorException(text)
  2072. def exec_command(self, text):
  2073. """
  2074. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2075. Also handles execution in separated threads
  2076. :param text:
  2077. :return: output if there was any
  2078. """
  2079. self.report_usage('exec_command')
  2080. result = self.exec_command_test(text, False)
  2081. #MS: added this method call so the geometry is updated once the TCL
  2082. #command is executed
  2083. self.plot_all()
  2084. return result
  2085. def exec_command_test(self, text, reraise=True):
  2086. """
  2087. Same as exec_command(...) with additional control over exceptions.
  2088. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2089. :param text: Input command
  2090. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2091. :return: Output from the command
  2092. """
  2093. text = str(text)
  2094. try:
  2095. self.shell.open_proccessing() # Disables input box.
  2096. result = self.tcl.eval(str(text))
  2097. if result != 'None':
  2098. self.shell.append_output(result + '\n')
  2099. except tk.TclError as e:
  2100. # This will display more precise answer if something in TCL shell fails
  2101. result = self.tcl.eval("set errorInfo")
  2102. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2103. self.shell.append_error('ERROR: ' + result + '\n')
  2104. # Show error in console and just return or in test raise exception
  2105. if reraise:
  2106. raise e
  2107. finally:
  2108. self.shell.close_proccessing()
  2109. pass
  2110. return result
  2111. # """
  2112. # Code below is unsused. Saved for later.
  2113. # """
  2114. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2115. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2116. # self.log.debug(parts)
  2117. # try:
  2118. # if parts[0] not in commands:
  2119. # self.shell.append_error("Unknown command\n")
  2120. # return
  2121. #
  2122. # #import inspect
  2123. # #inspect.getargspec(someMethod)
  2124. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2125. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2126. # self.shell.append_error(
  2127. # "Command %s takes %d arguments. %d given.\n" %
  2128. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2129. # )
  2130. # return
  2131. #
  2132. # cmdfcn = commands[parts[0]]["fcn"]
  2133. # cmdconv = commands[parts[0]]["converters"]
  2134. # if len(parts) - 1 > 0:
  2135. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2136. # else:
  2137. # retval = cmdfcn()
  2138. # retfcn = commands[parts[0]]["retfcn"]
  2139. # if retval and retfcn(retval):
  2140. # self.shell.append_output(retfcn(retval) + "\n")
  2141. #
  2142. # except Exception as e:
  2143. # #self.shell.append_error(''.join(traceback.format_exc()))
  2144. # #self.shell.append_error("?\n")
  2145. # self.shell.append_error(str(e) + "\n")
  2146. def info(self, msg):
  2147. """
  2148. Informs the user. Normally on the status bar, optionally
  2149. also on the shell.
  2150. :param msg: Text to write.
  2151. :return: None
  2152. """
  2153. # Type of message in brackets at the begining of the message.
  2154. match = re.search("\[([^\]]+)\](.*)", msg)
  2155. if match:
  2156. level = match.group(1)
  2157. msg_ = match.group(2)
  2158. self.ui.fcinfo.set_status(str(msg_), level=level)
  2159. if level.lower() == "error":
  2160. self.shell_message(msg, error=True, show=True)
  2161. elif level.lower() == "warning":
  2162. self.shell_message(msg, warning=True, show=True)
  2163. elif level.lower() == "error_notcl":
  2164. self.shell_message(msg, error=True, show=False)
  2165. elif level.lower() == "warning_notcl":
  2166. self.shell_message(msg, warning=True, show=False)
  2167. elif level.lower() == "success":
  2168. self.shell_message(msg, success=True, show=False)
  2169. elif level.lower() == "selected":
  2170. self.shell_message(msg, selected=True, show=False)
  2171. else:
  2172. self.shell_message(msg, show=False)
  2173. else:
  2174. self.ui.fcinfo.set_status(str(msg), level="info")
  2175. # make sure that if the message is to clear the infobar with a space
  2176. # is not printed over and over on the shell
  2177. if msg != '':
  2178. self.shell_message(msg)
  2179. def restore_toolbar_view(self):
  2180. tb = self.defaults["global_toolbar_view"]
  2181. if tb & 1:
  2182. self.ui.toolbarfile.setVisible(True)
  2183. else:
  2184. self.ui.toolbarfile.setVisible(False)
  2185. if tb & 2:
  2186. self.ui.toolbargeo.setVisible(True)
  2187. else:
  2188. self.ui.toolbargeo.setVisible(False)
  2189. if tb & 4:
  2190. self.ui.toolbarview.setVisible(True)
  2191. else:
  2192. self.ui.toolbarview.setVisible(False)
  2193. if tb & 8:
  2194. self.ui.toolbartools.setVisible(True)
  2195. else:
  2196. self.ui.toolbartools.setVisible(False)
  2197. if tb & 16:
  2198. self.ui.exc_edit_toolbar.setVisible(True)
  2199. else:
  2200. self.ui.exc_edit_toolbar.setVisible(False)
  2201. if tb & 32:
  2202. self.ui.geo_edit_toolbar.setVisible(True)
  2203. else:
  2204. self.ui.geo_edit_toolbar.setVisible(False)
  2205. if tb & 64:
  2206. self.ui.grb_edit_toolbar.setVisible(True)
  2207. else:
  2208. self.ui.grb_edit_toolbar.setVisible(False)
  2209. if tb & 128:
  2210. self.ui.snap_toolbar.setVisible(True)
  2211. else:
  2212. self.ui.snap_toolbar.setVisible(False)
  2213. if tb & 256:
  2214. self.ui.toolbarshell.setVisible(True)
  2215. else:
  2216. self.ui.toolbarshell.setVisible(False)
  2217. def load_defaults(self, filename):
  2218. """
  2219. Loads the aplication's default settings from current_defaults.FlatConfig into
  2220. ``self.defaults``.
  2221. :return: None
  2222. """
  2223. try:
  2224. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2225. options = f.read()
  2226. f.close()
  2227. except IOError:
  2228. self.log.error("Could not load defaults file.")
  2229. self.inform.emit(_("[ERROR] Could not load defaults file."))
  2230. # in case the defaults file can't be loaded, show all toolbars
  2231. self.defaults["global_toolbar_view"] = 511
  2232. return
  2233. try:
  2234. defaults = json.loads(options)
  2235. except:
  2236. # in case the defaults file can't be loaded, show all toolbars
  2237. self.defaults["global_toolbar_view"] = 511
  2238. e = sys.exc_info()[0]
  2239. App.log.error(str(e))
  2240. self.inform.emit(_("[ERROR] Failed to parse defaults file."))
  2241. return
  2242. self.defaults.update(defaults)
  2243. log.debug("FlatCAM defaults loaded from: %s" % filename)
  2244. # restore the toolbar view
  2245. self.restore_toolbar_view()
  2246. def on_import_preferences(self):
  2247. """
  2248. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  2249. ``self.defaults``.
  2250. :return: None
  2251. """
  2252. self.report_usage("on_import_preferences")
  2253. App.log.debug("on_import_preferences()")
  2254. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  2255. try:
  2256. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2257. directory=self.data_path, filter=filter)
  2258. except TypeError:
  2259. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"), filter=filter)
  2260. filename = str(filename)
  2261. if filename == "":
  2262. self.inform.emit(_("[WARNING_NOTCL] FlatCAM preferences import cancelled."))
  2263. else:
  2264. try:
  2265. f = open(filename)
  2266. options = f.read()
  2267. f.close()
  2268. except IOError:
  2269. self.log.error("Could not load defaults file.")
  2270. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2271. return
  2272. try:
  2273. defaults_from_file = json.loads(options)
  2274. except:
  2275. e = sys.exc_info()[0]
  2276. App.log.error(str(e))
  2277. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2278. return
  2279. self.defaults.update(defaults_from_file)
  2280. self.inform.emit(_("[success] Imported Defaults from %s") %filename)
  2281. def on_export_preferences(self):
  2282. self.report_usage("on_export_preferences")
  2283. App.log.debug("on_export_preferences()")
  2284. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  2285. try:
  2286. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  2287. caption=_("Export FlatCAM Preferences"),
  2288. directory=self.data_path + '/preferences_' + self.date, filter=filter
  2289. )
  2290. except TypeError:
  2291. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"), filter=filter)
  2292. filename = str(filename)
  2293. defaults_from_file = {}
  2294. if filename == "":
  2295. self.inform.emit(_("[WARNING_NOTCL] FlatCAM preferences export cancelled."))
  2296. return
  2297. else:
  2298. try:
  2299. f = open(filename, 'w')
  2300. defaults_file_content = f.read()
  2301. f.close()
  2302. except IOError:
  2303. App.log.debug('Creating a new preferences file ...')
  2304. f = open(filename, 'w')
  2305. json.dump({}, f)
  2306. f.close()
  2307. except:
  2308. e = sys.exc_info()[0]
  2309. App.log.error("Could not load defaults file.")
  2310. App.log.error(str(e))
  2311. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2312. return
  2313. try:
  2314. defaults_from_file = json.loads(defaults_file_content)
  2315. except:
  2316. App.log.warning("Trying to read an empty Preferences file. Continue.")
  2317. # Update options
  2318. self.defaults_read_form()
  2319. defaults_from_file.update(self.defaults)
  2320. self.propagate_defaults(silent=True)
  2321. # Save update options
  2322. try:
  2323. f = open(filename, "w")
  2324. json.dump(defaults_from_file, f)
  2325. f.close()
  2326. except:
  2327. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  2328. return
  2329. if self.defaults["global_open_style"] is False:
  2330. self.file_opened.emit("preferences", filename)
  2331. self.file_saved.emit("preferences", filename)
  2332. self.inform.emit("[success] Exported Defaults to %s" % filename)
  2333. def on_preferences_open_folder(self):
  2334. self.report_usage("on_preferences_open_folder()")
  2335. if sys.platform == 'win32':
  2336. subprocess.Popen('explorer %s' % self.data_path)
  2337. elif sys.platform == 'darwin':
  2338. os.system('open "%s"' % self.data_path)
  2339. else:
  2340. subprocess.Popen(['xdg-open', self.data_path])
  2341. self.inform.emit("[success] FlatCAM Preferences Folder opened.")
  2342. def save_geometry(self, x, y, width, height, notebook_width):
  2343. self.defaults["global_def_win_x"] = x
  2344. self.defaults["global_def_win_y"] = y
  2345. self.defaults["global_def_win_w"] = width
  2346. self.defaults["global_def_win_h"] = height
  2347. self.defaults["global_def_notebook_width"] = notebook_width
  2348. self.save_defaults()
  2349. def message_dialog(self, title, message, kind="info"):
  2350. icon = {"info": QtWidgets.QMessageBox.Information,
  2351. "warning": QtWidgets.QMessageBox.Warning,
  2352. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2353. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2354. dlg.setText(message)
  2355. dlg.exec_()
  2356. def register_recent(self, kind, filename):
  2357. self.log.debug("register_recent()")
  2358. self.log.debug(" %s" % kind)
  2359. self.log.debug(" %s" % filename)
  2360. record = {'kind': str(kind), 'filename': str(filename)}
  2361. if record in self.recent:
  2362. return
  2363. self.recent.insert(0, record)
  2364. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2365. self.recent.pop()
  2366. try:
  2367. f = open(self.data_path + '/recent.json', 'w')
  2368. except IOError:
  2369. App.log.error("Failed to open recent items file for writing.")
  2370. self.inform.emit(_('[ERROR_NOTCL] Failed to open recent files file for writing.'))
  2371. return
  2372. #try:
  2373. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2374. # except:
  2375. # App.log.error("Failed to write to recent items file.")
  2376. # self.inform.emit('ERROR: Failed to write to recent items file.')
  2377. # f.close()
  2378. f.close()
  2379. # Re-buid the recent items menu
  2380. self.setup_recent_items()
  2381. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2382. """
  2383. Creates a new specialized FlatCAMObj and attaches it to the application,
  2384. this is, updates the GUI accordingly, any other records and plots it.
  2385. This method is thread-safe.
  2386. Notes:
  2387. * If the name is in use, the self.collection will modify it
  2388. when appending it to the collection. There is no need to handle
  2389. name conflicts here.
  2390. :param kind: The kind of object to create. One of 'gerber',
  2391. 'excellon', 'cncjob' and 'geometry'.
  2392. :type kind: str
  2393. :param name: Name for the object.
  2394. :type name: str
  2395. :param initialize: Function to run after creation of the object
  2396. but before it is attached to the application. The function is
  2397. called with 2 parameters: the new object and the App instance.
  2398. :type initialize: function
  2399. :return: None
  2400. :rtype: None
  2401. """
  2402. App.log.debug("new_object()")
  2403. obj_plot = plot
  2404. obj_autoselected = autoselected
  2405. t0 = time.time() # Debug
  2406. ## Create object
  2407. classdict = {
  2408. "gerber": FlatCAMGerber,
  2409. "excellon": FlatCAMExcellon,
  2410. "cncjob": FlatCAMCNCjob,
  2411. "geometry": FlatCAMGeometry
  2412. }
  2413. App.log.debug("Calling object constructor...")
  2414. obj = classdict[kind](name)
  2415. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  2416. # Set options from "Project options" form
  2417. self.options_read_form()
  2418. # IMPORTANT
  2419. # The key names in defaults and options dictionary's are not random:
  2420. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2421. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  2422. # the options from project options form into the self.options. After that, below, depending on the type of
  2423. # object that is created, it will strip the name of the object and the underline (if the original key was
  2424. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2425. # "toolchange"
  2426. for option in self.options:
  2427. if option.find(kind + "_") == 0:
  2428. oname = option[len(kind) + 1:]
  2429. obj.options[oname] = self.options[option]
  2430. obj.isHovering = False
  2431. obj.notHovering = True
  2432. # Initialize as per user request
  2433. # User must take care to implement initialize
  2434. # in a thread-safe way as is is likely that we
  2435. # have been invoked in a separate thread.
  2436. t1 = time.time()
  2437. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2438. try:
  2439. return_value = initialize(obj, self)
  2440. except Exception as e:
  2441. msg = _("[ERROR_NOTCL] An internal error has ocurred. See shell.\n")
  2442. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2443. msg += traceback.format_exc()
  2444. self.inform.emit(msg)
  2445. # if str(e) == "Empty Geometry":
  2446. # self.inform.emit("[ERROR_NOTCL] )
  2447. # else:
  2448. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  2449. return "fail"
  2450. t2 = time.time()
  2451. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2452. if return_value == 'fail':
  2453. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2454. return "fail"
  2455. # Check units and convert if necessary
  2456. # This condition CAN be true because initialize() can change obj.units
  2457. if self.options["units"].upper() != obj.units.upper():
  2458. self.inform.emit(_("Converting units to ") + self.options["units"] + ".")
  2459. obj.convert_units(self.options["units"])
  2460. t3 = time.time()
  2461. self.log.debug("%f seconds converting units." % (t3 - t2))
  2462. # Create the bounding box for the object and then add the results to the obj.options
  2463. try:
  2464. xmin, ymin, xmax, ymax = obj.bounds()
  2465. obj.options['xmin'] = xmin
  2466. obj.options['ymin'] = ymin
  2467. obj.options['xmax'] = xmax
  2468. obj.options['ymax'] = ymax
  2469. except:
  2470. log.warning("The object has no bounds properties.")
  2471. # don't plot objects with no bounds, there is nothing to plot
  2472. self.plot = False
  2473. pass
  2474. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  2475. # Move the object to the main thread and let the app know that it is available.
  2476. obj.moveToThread(self.main_thread)
  2477. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2478. return obj
  2479. def new_excellon_object(self):
  2480. self.report_usage("new_excellon_object()")
  2481. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2482. def new_geometry_object(self):
  2483. self.report_usage("new_geometry_object()")
  2484. def initialize(obj, self):
  2485. obj.multitool = False
  2486. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2487. def new_gerber_object(self):
  2488. self.report_usage("new_gerber_object()")
  2489. def initialize(grb_obj, self):
  2490. grb_obj.multitool = False
  2491. grb_obj.source_file = []
  2492. grb_obj.multigeo = False
  2493. grb_obj.follow = False
  2494. grb_obj.apertures = {}
  2495. grb_obj.solid_geometry = []
  2496. try:
  2497. grb_obj.options['xmin'] = 0
  2498. grb_obj.options['ymin'] = 0
  2499. grb_obj.options['xmax'] = 0
  2500. grb_obj.options['ymax'] = 0
  2501. except KeyError:
  2502. pass
  2503. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2504. def on_object_created(self, obj, plot, autoselect):
  2505. """
  2506. Event callback for object creation.
  2507. :param obj: The newly created FlatCAM object.
  2508. :return: None
  2509. """
  2510. t0 = time.time() # DEBUG
  2511. self.log.debug("on_object_created()")
  2512. # The Collection might change the name if there is a collision
  2513. self.collection.append(obj)
  2514. # after adding the object to the collection always update the list of objects that are in the collection
  2515. self.all_objects_list = self.collection.get_list()
  2516. # self.inform.emit('[selected] %s created & selected: %s' %
  2517. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2518. if obj.kind == 'gerber':
  2519. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2520. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  2521. elif obj.kind == 'excellon':
  2522. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2523. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  2524. elif obj.kind == 'cncjob':
  2525. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2526. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  2527. elif obj.kind == 'geometry':
  2528. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2529. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  2530. # update the SHELL auto-completer model with the name of the new object
  2531. self.myKeywords.append(obj.options['name'])
  2532. self.shell._edit.set_model_data(self.myKeywords)
  2533. self.ui.code_editor.set_model_data(self.myKeywords)
  2534. if autoselect:
  2535. # select the just opened object but deselect the previous ones
  2536. self.collection.set_all_inactive()
  2537. self.collection.set_active(obj.options["name"])
  2538. # here it is done the object plotting
  2539. def worker_task(obj):
  2540. with self.proc_container.new("Plotting"):
  2541. if isinstance(obj, FlatCAMCNCjob):
  2542. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2543. else:
  2544. obj.plot()
  2545. t1 = time.time() # DEBUG
  2546. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2547. self.object_plotted.emit(obj)
  2548. # Send to worker
  2549. # self.worker.add_task(worker_task, [self])
  2550. if plot is True:
  2551. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2552. def on_object_changed(self, obj):
  2553. # update the bounding box data from obj.options
  2554. xmin, ymin, xmax, ymax = obj.bounds()
  2555. obj.options['xmin'] = xmin
  2556. obj.options['ymin'] = ymin
  2557. obj.options['xmax'] = xmax
  2558. obj.options['ymax'] = ymax
  2559. log.debug("Object changed, updating the bounding box data on self.options")
  2560. # delete the old selection shape
  2561. self.delete_selection_shape()
  2562. self.should_we_save = True
  2563. def on_object_plotted(self, obj):
  2564. self.on_zoom_fit(None)
  2565. def options_read_form(self):
  2566. for option in self.options_form_fields:
  2567. self.options[option] = self.options_form_fields[option].get_value()
  2568. def options_write_form(self):
  2569. for option in self.options:
  2570. self.options_write_form_field(option)
  2571. def options_write_form_field(self, field):
  2572. try:
  2573. self.options_form_fields[field].set_value(self.options[field])
  2574. except KeyError:
  2575. # Changed from error to debug. This allows to have data stored
  2576. # which is not user-editable.
  2577. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  2578. pass
  2579. def on_about(self):
  2580. """
  2581. Displays the "about" dialog.
  2582. :return: None
  2583. """
  2584. self.report_usage("on_about")
  2585. version = self.version
  2586. version_date = self.version_date
  2587. beta = self.beta
  2588. class AboutDialog(QtWidgets.QDialog):
  2589. def __init__(self, parent=None):
  2590. QtWidgets.QDialog.__init__(self, parent)
  2591. # Icon and title
  2592. self.setWindowIcon(parent.app_icon)
  2593. self.setWindowTitle("FlatCAM")
  2594. layout1 = QtWidgets.QVBoxLayout()
  2595. self.setLayout(layout1)
  2596. layout2 = QtWidgets.QHBoxLayout()
  2597. layout1.addLayout(layout2)
  2598. logo = QtWidgets.QLabel()
  2599. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  2600. layout2.addWidget(logo, stretch=0)
  2601. title = QtWidgets.QLabel(
  2602. _(
  2603. "<font size=8><B>FlatCAM</B></font><BR>"
  2604. "Version {version} {beta} ({date}) - {arch} <BR>"
  2605. "<BR>"
  2606. "2D Computer-Aided Printed Circuit Board<BR>"
  2607. "Manufacturing.<BR>"
  2608. "<BR>"
  2609. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  2610. "<BR>"
  2611. "<B> Main Contributors:</B><BR>"
  2612. "Denis Hayrullin<BR>"
  2613. "Kamil Sopko<BR>"
  2614. "Marius Stanciu<BR>"
  2615. "Matthieu Berthomé<BR>"
  2616. "and many others found "
  2617. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  2618. "<BR>"
  2619. "Development is done "
  2620. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  2621. "DOWNLOAD area "
  2622. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  2623. ""
  2624. ).format(version=version,
  2625. beta=('BETA' if beta else ''),
  2626. date=version_date,
  2627. arch=platform.architecture()[0])
  2628. )
  2629. title.setOpenExternalLinks(True)
  2630. layout2.addWidget(title, stretch=1)
  2631. layout3 = QtWidgets.QHBoxLayout()
  2632. layout1.addLayout(layout3)
  2633. layout3.addStretch()
  2634. okbtn = QtWidgets.QPushButton("Close")
  2635. layout3.addWidget(okbtn)
  2636. okbtn.clicked.connect(self.accept)
  2637. AboutDialog(self.ui).exec_()
  2638. def on_file_savedefaults(self):
  2639. """
  2640. Callback for menu item File->Save Defaults. Saves application default options
  2641. ``self.defaults`` to current_defaults.FlatConfig.
  2642. :return: None
  2643. """
  2644. self.save_defaults()
  2645. # def on_app_exit(self):
  2646. # self.report_usage("on_app_exit()")
  2647. #
  2648. # if self.collection.get_list():
  2649. # msgbox = QtWidgets.QMessageBox()
  2650. # # msgbox.setText("<B>Save changes ...</B>")
  2651. # msgbox.setText("There are files/objects opened in FlatCAM. "
  2652. # "\n"
  2653. # "Do you want to Save the project?")
  2654. # msgbox.setWindowTitle("Save changes")
  2655. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2656. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2657. # QtWidgets.QMessageBox.Cancel)
  2658. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2659. #
  2660. # response = msgbox.exec_()
  2661. #
  2662. # if response == QtWidgets.QMessageBox.Yes:
  2663. # self.on_file_saveprojectas(thread=False)
  2664. # elif response == QtWidgets.QMessageBox.Cancel:
  2665. # return
  2666. # self.save_defaults()
  2667. # else:
  2668. # self.save_defaults()
  2669. # log.debug("Application defaults saved ... Exit event.")
  2670. # QtWidgets.qApp.quit()
  2671. def save_defaults(self, silent=False):
  2672. """
  2673. Saves application default options
  2674. ``self.defaults`` to current_defaults.FlatConfig.
  2675. :return: None
  2676. """
  2677. self.report_usage("save_defaults")
  2678. # Read options from file
  2679. try:
  2680. f = open(self.data_path + "/current_defaults.FlatConfig")
  2681. defaults_file_content = f.read()
  2682. f.close()
  2683. except:
  2684. e = sys.exc_info()[0]
  2685. App.log.error("Could not load defaults file.")
  2686. App.log.error(str(e))
  2687. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2688. return
  2689. try:
  2690. defaults = json.loads(defaults_file_content)
  2691. except:
  2692. e = sys.exc_info()[0]
  2693. App.log.error("Failed to parse defaults file.")
  2694. App.log.error(str(e))
  2695. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2696. return
  2697. # Update options
  2698. self.defaults_read_form()
  2699. defaults.update(self.defaults)
  2700. self.propagate_defaults(silent=True)
  2701. # Save the toolbar view
  2702. tb_status = 0
  2703. if self.ui.toolbarfile.isVisible():
  2704. tb_status += 1
  2705. if self.ui.toolbargeo.isVisible():
  2706. tb_status += 2
  2707. if self.ui.toolbarview.isVisible():
  2708. tb_status += 4
  2709. if self.ui.toolbartools.isVisible():
  2710. tb_status += 8
  2711. if self.ui.exc_edit_toolbar.isVisible():
  2712. tb_status += 16
  2713. if self.ui.geo_edit_toolbar.isVisible():
  2714. tb_status += 32
  2715. if self.ui.grb_edit_toolbar.isVisible():
  2716. tb_status += 64
  2717. if self.ui.snap_toolbar.isVisible():
  2718. tb_status += 128
  2719. if self.ui.toolbarshell.isVisible():
  2720. tb_status += 256
  2721. self.defaults["global_toolbar_view"] = tb_status
  2722. # Save update options
  2723. try:
  2724. f = open(self.data_path + "/current_defaults.FlatConfig", "w")
  2725. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  2726. f.close()
  2727. except:
  2728. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  2729. return
  2730. if not silent:
  2731. self.inform.emit(_("[success] Defaults saved."))
  2732. def save_factory_defaults(self, silent=False):
  2733. """
  2734. Saves application factory default options
  2735. ``self.defaults`` to factory_defaults.FlatConfig.
  2736. It's a one time job done just after the first install.
  2737. :return: None
  2738. """
  2739. self.report_usage("save_factory_defaults")
  2740. # Read options from file
  2741. try:
  2742. f_f_def = open(self.data_path + "/factory_defaults.FlatConfig")
  2743. factory_defaults_file_content = f_f_def.read()
  2744. f_f_def.close()
  2745. except:
  2746. e = sys.exc_info()[0]
  2747. App.log.error("Could not load factory defaults file.")
  2748. App.log.error(str(e))
  2749. self.inform.emit(_("[ERROR_NOTCL] Could not load factory defaults file."))
  2750. return
  2751. try:
  2752. factory_defaults = json.loads(factory_defaults_file_content)
  2753. except:
  2754. e = sys.exc_info()[0]
  2755. App.log.error("Failed to parse factory defaults file.")
  2756. App.log.error(str(e))
  2757. self.inform.emit(_("[ERROR_NOTCL] Failed to parse factory defaults file."))
  2758. return
  2759. # Update options
  2760. self.defaults_read_form()
  2761. factory_defaults.update(self.defaults)
  2762. self.propagate_defaults(silent=True)
  2763. # Save update options
  2764. try:
  2765. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  2766. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  2767. f_f_def_s.close()
  2768. except:
  2769. self.inform.emit(_("[ERROR_NOTCL] Failed to write factory defaults to file."))
  2770. return
  2771. if silent is False:
  2772. self.inform.emit(_("Factory defaults saved."))
  2773. def final_save(self):
  2774. if self.save_in_progress:
  2775. self.inform.emit(_("[WARNING_NOTCL] Application is saving the project. Please wait ..."))
  2776. return
  2777. if self.should_we_save and self.collection.get_list():
  2778. msgbox = QtWidgets.QMessageBox()
  2779. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2780. "\n"
  2781. "Do you want to Save the project?"))
  2782. msgbox.setWindowTitle(_("Save changes"))
  2783. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2784. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2785. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2786. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2787. msgbox.setDefaultButton(bt_yes)
  2788. msgbox.exec_()
  2789. response = msgbox.clickedButton()
  2790. if response == bt_yes:
  2791. self.on_file_saveprojectas(thread=True, quit=True)
  2792. elif response == bt_no:
  2793. self.quit_application()
  2794. elif response == bt_cancel:
  2795. return
  2796. else:
  2797. self.quit_application()
  2798. def quit_application(self):
  2799. self.save_defaults()
  2800. log.debug("App.final_save() --> App Defaults saved.")
  2801. # save toolbar state to file
  2802. settings = QSettings("Open Source", "FlatCAM")
  2803. settings.setValue('saved_gui_state', self.ui.saveState())
  2804. settings.setValue('maximized_gui', self.ui.isMaximized())
  2805. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  2806. # This will write the setting to the platform specific storage.
  2807. del settings
  2808. log.debug("App.final_save() --> App UI state saved.")
  2809. QtWidgets.qApp.quit()
  2810. def on_toggle_shell(self):
  2811. """
  2812. toggle shell if is visible close it if closed open it
  2813. :return:
  2814. """
  2815. self.report_usage("on_toggle_shell()")
  2816. if self.ui.shell_dock.isVisible():
  2817. self.ui.shell_dock.hide()
  2818. else:
  2819. self.ui.shell_dock.show()
  2820. def on_edit_join(self, name=None):
  2821. """
  2822. Callback for Edit->Join. Joins the selected geometry objects into
  2823. a new one.
  2824. :return: None
  2825. """
  2826. self.report_usage("on_edit_join()")
  2827. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2828. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2829. tooldias = []
  2830. geo_type_list = []
  2831. objs = self.collection.get_selected()
  2832. for obj in objs:
  2833. geo_type_list.append(obj.multigeo)
  2834. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  2835. if len(set(geo_type_list)) != 1:
  2836. self.inform.emit(_("[ERROR] Failed join. The Geometry objects are of different types.\n"
  2837. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2838. "convert from one to another and retry joining \n"
  2839. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2840. "the result may not be what was expected. \n"
  2841. "Check the generated GCODE."))
  2842. return
  2843. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2844. if True in geo_type_list:
  2845. def initialize(obj, app):
  2846. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  2847. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2848. for v in obj.tools.values():
  2849. v['data']['name'] = obj_name_multi
  2850. self.new_object("geometry", obj_name_multi, initialize)
  2851. else:
  2852. def initialize(obj, app):
  2853. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  2854. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2855. for v in obj.tools.values():
  2856. v['data']['name'] = obj_name_single
  2857. self.new_object("geometry", obj_name_single, initialize)
  2858. self.should_we_save = True
  2859. def on_edit_join_exc(self):
  2860. """
  2861. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  2862. a new one.
  2863. :return: None
  2864. """
  2865. self.report_usage("on_edit_join_exc()")
  2866. objs = self.collection.get_selected()
  2867. for obj in objs:
  2868. if not isinstance(obj, FlatCAMExcellon):
  2869. self.inform.emit(_("[ERROR_NOTCL] Failed. Excellon joining works only on Excellon objects."))
  2870. return
  2871. def initialize(obj, app):
  2872. FlatCAMExcellon.merge(objs, obj)
  2873. self.new_object("excellon", 'Combo_Excellon', initialize)
  2874. self.should_we_save = True
  2875. def on_edit_join_grb(self):
  2876. """
  2877. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2878. a new one.
  2879. :return: None
  2880. """
  2881. self.report_usage("on_edit_join_grb()")
  2882. objs = self.collection.get_selected()
  2883. for obj in objs:
  2884. if not isinstance(obj, FlatCAMGerber):
  2885. self.inform.emit(_("[ERROR_NOTCL] Failed. Gerber joining works only on Gerber objects."))
  2886. return
  2887. def initialize(obj, app):
  2888. FlatCAMGerber.merge(objs, obj)
  2889. self.new_object("gerber", 'Combo_Gerber', initialize)
  2890. self.should_we_save = True
  2891. def on_convert_singlegeo_to_multigeo(self):
  2892. self.report_usage("on_convert_singlegeo_to_multigeo()")
  2893. obj = self.collection.get_active()
  2894. if obj is None:
  2895. self.inform.emit(_("[ERROR_NOTCL] Failed. Select a Geometry Object and try again."))
  2896. return
  2897. if not isinstance(obj, FlatCAMGeometry):
  2898. self.inform.emit(_("[ERROR_NOTCL] Expected a FlatCAMGeometry, got %s") % type(obj))
  2899. return
  2900. obj.multigeo = True
  2901. for tooluid, dict_value in obj.tools.items():
  2902. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2903. if not isinstance(obj.solid_geometry, list):
  2904. obj.solid_geometry = [obj.solid_geometry]
  2905. obj.solid_geometry[:] = []
  2906. obj.plot()
  2907. self.should_we_save = True
  2908. self.inform.emit(_("[success] A Geometry object was converted to MultiGeo type."))
  2909. def on_convert_multigeo_to_singlegeo(self):
  2910. self.report_usage("on_convert_multigeo_to_singlegeo()")
  2911. obj = self.collection.get_active()
  2912. if obj is None:
  2913. self.inform.emit(_("[ERROR_NOTCL] Failed. Select a Geometry Object and try again."))
  2914. return
  2915. if not isinstance(obj, FlatCAMGeometry):
  2916. self.inform.emit(_("[ERROR_NOTCL] Expected a FlatCAMGeometry, got %s") % type(obj))
  2917. return
  2918. obj.multigeo = False
  2919. total_solid_geometry = []
  2920. for tooluid, dict_value in obj.tools.items():
  2921. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  2922. # clear the original geometry
  2923. dict_value['solid_geometry'][:] = []
  2924. obj.solid_geometry = deepcopy(total_solid_geometry)
  2925. obj.plot()
  2926. self.should_we_save = True
  2927. self.inform.emit(_("[success] A Geometry object was converted to SingleGeo type."))
  2928. def on_options_dict_change(self, field):
  2929. self.options_write_form_field(field)
  2930. if field == "units":
  2931. self.set_screen_units(self.options['units'])
  2932. def on_defaults_dict_change(self, field):
  2933. self.defaults_write_form_field(field)
  2934. if field == "units":
  2935. self.set_screen_units(self.defaults['units'])
  2936. def set_screen_units(self, units):
  2937. self.ui.units_label.setText("[" + self.defaults["units"].lower() + "]")
  2938. def on_toggle_units(self, no_pref=False):
  2939. """
  2940. Callback for the Units radio-button change in the Options tab.
  2941. Changes the application's default units or the current project's units.
  2942. If changing the project's units, the change propagates to all of
  2943. the objects in the project.
  2944. :return: None
  2945. """
  2946. self.report_usage("on_toggle_units")
  2947. if self.toggle_units_ignore:
  2948. return
  2949. # If option is the same, then ignore
  2950. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == \
  2951. self.defaults["units"].upper():
  2952. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  2953. return
  2954. # Options to scale
  2955. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  2956. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  2957. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  2958. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  2959. "excellon_z_pdepth",
  2960. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  2961. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  2962. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  2963. "geometry_feedrate_probe",
  2964. 'cncjob_tooldia',
  2965. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  2966. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin",
  2967. "tools_2sided_drilldia", "tools_film_boundary",
  2968. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  2969. "tools_panelize_constrainx", "tools_panelize_constrainy",
  2970. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  2971. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  2972. "tools_transform_offset_y",
  2973. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  2974. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  2975. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  2976. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  2977. 'global_gridx', 'global_gridy', 'global_snap_max']
  2978. def scale_options(sfactor):
  2979. for dim in dimensions:
  2980. if dim == 'excellon_toolchangexy':
  2981. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2982. coords_xy[0] *= sfactor
  2983. coords_xy[1] *= sfactor
  2984. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2985. elif dim == 'geometry_toolchangexy':
  2986. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2987. coords_xy[0] *= sfactor
  2988. coords_xy[1] *= sfactor
  2989. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2990. elif dim == 'tools_ncctools':
  2991. ncctols = [float(eval(a)) for a in self.defaults["tools_ncctools"].split(",")]
  2992. ncctols[0] *= sfactor
  2993. ncctols[1] *= sfactor
  2994. self.options['tools_ncctools'] = "%f, %f" % (ncctols[0], ncctols[1])
  2995. elif dim == 'tools_solderpaste_tools':
  2996. sp_tools = [float(eval(a)) for a in self.defaults["tools_solderpaste_tools"].split(",")]
  2997. sp_tools[0] *= sfactor
  2998. sp_tools[1] *= sfactor
  2999. self.options['tools_solderpaste_tools'] = "%f, %f" % (sp_tools[0], sp_tools[1])
  3000. elif dim == 'tools_solderpaste_xy_toolchange':
  3001. sp_coords = [float(eval(a)) for a in self.defaults["tools_solderpaste_xy_toolchange"].split(",")]
  3002. sp_coords[0] *= sfactor
  3003. sp_coords[1] *= sfactor
  3004. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  3005. else:
  3006. try:
  3007. self.options[dim] = float(self.options[dim]) * sfactor
  3008. except Exception as e:
  3009. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  3010. def scale_defaults(sfactor):
  3011. for dim in dimensions:
  3012. if dim == 'excellon_toolchangexy':
  3013. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  3014. coords_xy[0] *= sfactor
  3015. coords_xy[1] *= sfactor
  3016. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  3017. elif dim == 'geometry_toolchangexy':
  3018. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  3019. coords_xy[0] *= sfactor
  3020. coords_xy[1] *= sfactor
  3021. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  3022. elif dim == 'tools_ncctools':
  3023. ncctols = [float(eval(a)) for a in self.defaults["tools_ncctools"].split(",")]
  3024. ncctols[0] *= sfactor
  3025. ncctols[1] *= sfactor
  3026. self.defaults['tools_ncctools'] = "%.4f, %.4f" % (ncctols[0], ncctols[1])
  3027. elif dim == 'tools_solderpaste_tools':
  3028. sp_tools = [float(eval(a)) for a in self.defaults["tools_solderpaste_tools"].split(",")]
  3029. sp_tools[0] *= sfactor
  3030. sp_tools[1] *= sfactor
  3031. self.defaults['tools_solderpaste_tools'] = "%.4f, %.4f" % (sp_tools[0], sp_tools[1])
  3032. elif dim == 'tools_solderpaste_xy_toolchange':
  3033. sp_coords = [float(eval(a)) for a in self.defaults["tools_solderpaste_xy_toolchange"].split(",")]
  3034. sp_coords[0] *= sfactor
  3035. sp_coords[1] *= sfactor
  3036. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  3037. else:
  3038. try:
  3039. self.defaults[dim] = float(self.defaults[dim]) * sfactor
  3040. except Exception as e:
  3041. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3042. # The scaling factor depending on choice of units.
  3043. factor = 1/25.4
  3044. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  3045. factor = 25.4
  3046. # Changing project units. Warn user.
  3047. msgbox = QtWidgets.QMessageBox()
  3048. msgbox.setWindowTitle("Toggle Units")
  3049. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  3050. msgbox.setText("<B>Change project units ...</B>")
  3051. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  3052. "properties of all objects to be scaled accordingly.\nContinue?")
  3053. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3054. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3055. msgbox.setDefaultButton(bt_ok)
  3056. msgbox.exec_()
  3057. response = msgbox.clickedButton()
  3058. if response == bt_ok:
  3059. if no_pref is False:
  3060. self.options_read_form()
  3061. scale_options(factor)
  3062. self.options_write_form()
  3063. self.defaults_read_form()
  3064. scale_defaults(factor)
  3065. self.defaults_write_form()
  3066. self.should_we_save = True
  3067. # change this only if the workspace is active
  3068. if self.defaults['global_workspace'] is True:
  3069. self.plotcanvas.draw_workspace()
  3070. # adjust the grid values on the main toolbar
  3071. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  3072. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  3073. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3074. for obj in self.collection.get_list():
  3075. obj.convert_units(units)
  3076. # make that the properties stored in the object are also updated
  3077. self.object_changed.emit(obj)
  3078. obj.build_ui()
  3079. current = self.collection.get_active()
  3080. if current is not None:
  3081. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3082. if not isinstance(current, FlatCAMGeometry):
  3083. current.to_form()
  3084. self.plot_all()
  3085. self.inform.emit(_("[success] Converted units to %s") % units)
  3086. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  3087. self.set_screen_units(units)
  3088. else:
  3089. # Undo toggling
  3090. self.toggle_units_ignore = True
  3091. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  3092. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3093. else:
  3094. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3095. self.toggle_units_ignore = False
  3096. self.inform.emit(_("[WARNING_NOTCL] Units conversion cancelled."))
  3097. self.options_read_form()
  3098. self.defaults_read_form()
  3099. def on_toggle_units_click(self):
  3100. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3101. if self.defaults["units"] == 'MM':
  3102. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3103. else:
  3104. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3105. self.on_toggle_units(no_pref=True)
  3106. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3107. lambda: self.on_toggle_units(no_pref=False))
  3108. def on_fullscreen(self):
  3109. self.report_usage("on_fullscreen()")
  3110. if self.toggle_fscreen is False:
  3111. if sys.platform == 'win32':
  3112. self.ui.showFullScreen()
  3113. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3114. tb.setVisible(False)
  3115. self.ui.splitter_left.setVisible(False)
  3116. self.toggle_fscreen = True
  3117. else:
  3118. if sys.platform == 'win32':
  3119. self.ui.showNormal()
  3120. self.restore_toolbar_view()
  3121. self.ui.splitter_left.setVisible(True)
  3122. self.toggle_fscreen = False
  3123. def on_toggle_plotarea(self):
  3124. self.report_usage("on_toggle_plotarea()")
  3125. try:
  3126. name = self.ui.plot_tab_area.widget(0).objectName()
  3127. except AttributeError:
  3128. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3129. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3130. self.ui.plot_tab_area.protectTab(0)
  3131. return
  3132. if name != 'plotarea':
  3133. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3134. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3135. self.ui.plot_tab_area.protectTab(0)
  3136. else:
  3137. self.ui.plot_tab_area.closeTab(0)
  3138. def on_toggle_notebook(self):
  3139. if self.ui.splitter.sizes()[0] == 0:
  3140. self.ui.splitter.setSizes([1, 1])
  3141. else:
  3142. self.ui.splitter.setSizes([0, 1])
  3143. def on_toggle_axis(self):
  3144. self.report_usage("on_toggle_axis()")
  3145. if self.toggle_axis is False:
  3146. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  3147. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  3148. self.plotcanvas.redraw()
  3149. self.toggle_axis = True
  3150. else:
  3151. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  3152. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  3153. self.plotcanvas.redraw()
  3154. self.toggle_axis = False
  3155. def on_toggle_grid(self):
  3156. self.report_usage("on_toggle_grid()")
  3157. self.ui.grid_snap_btn.trigger()
  3158. def on_options_combo_change(self, sel):
  3159. """
  3160. Called when the combo box to choose between application defaults and
  3161. project option changes value. The corresponding variables are
  3162. copied to the UI.
  3163. :param sel: The option index that was chosen.
  3164. :return: None
  3165. """
  3166. # combo_sel = self.ui.notebook.combo_options.get_active()
  3167. App.log.debug("Options --> %s" % sel)
  3168. # form = [self.defaults_form, self.options_form][sel]
  3169. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  3170. if sel == 0:
  3171. self.gen_form = self.ui.general_defaults_form
  3172. self.ger_form = self.ui.gerber_defaults_form
  3173. self.exc_form = self.ui.excellon_defaults_form
  3174. self.geo_form = self.ui.geometry_defaults_form
  3175. self.cnc_form = self.ui.cncjob_defaults_form
  3176. self.tools_form = self.ui.tools_defaults_form
  3177. elif sel == 1:
  3178. self.gen_form = self.ui.general_options_form
  3179. self.ger_form = self.ui.gerber_options_form
  3180. self.exc_form = self.ui.excellon_options_form
  3181. self.geo_form = self.ui.geometry_options_form
  3182. self.cnc_form = self.ui.cncjob_options_form
  3183. self.tools_form = self.ui.tools_options_form
  3184. else:
  3185. return
  3186. try:
  3187. self.ui.general_scroll_area.takeWidget()
  3188. except:
  3189. self.log.debug("Nothing to remove")
  3190. self.ui.general_scroll_area.setWidget(self.gen_form)
  3191. self.gen_form.show()
  3192. try:
  3193. self.ui.gerber_scroll_area.takeWidget()
  3194. except:
  3195. self.log.debug("Nothing to remove")
  3196. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  3197. self.ger_form.show()
  3198. try:
  3199. self.ui.excellon_scroll_area.takeWidget()
  3200. except:
  3201. self.log.debug("Nothing to remove")
  3202. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  3203. self.exc_form.show()
  3204. try:
  3205. self.ui.geometry_scroll_area.takeWidget()
  3206. except:
  3207. self.log.debug("Nothing to remove")
  3208. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  3209. self.geo_form.show()
  3210. try:
  3211. self.ui.cncjob_scroll_area.takeWidget()
  3212. except:
  3213. self.log.debug("Nothing to remove")
  3214. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  3215. self.cnc_form.show()
  3216. try:
  3217. self.ui.tools_scroll_area.takeWidget()
  3218. except:
  3219. self.log.debug("Nothing to remove")
  3220. self.ui.tools_scroll_area.setWidget(self.tools_form)
  3221. self.tools_form.show()
  3222. self.log.debug("Finished GUI form initialization.")
  3223. # self.options2form()
  3224. def on_excellon_defaults_button(self):
  3225. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  3226. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  3227. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  3228. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  3229. self.defaults_form_fields["excellon_zeros"].set_value('L')
  3230. self.defaults_form_fields["excellon_units"].set_value('INCH')
  3231. log.debug("Excellon app defaults loaded ...")
  3232. def on_excellon_options_button(self):
  3233. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  3234. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  3235. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  3236. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  3237. self.options_form_fields["excellon_zeros"].set_value('L')
  3238. self.options_form_fields["excellon_units"].set_value('INCH')
  3239. log.debug("Excellon options defaults loaded ...")
  3240. # Setting plot colors handlers
  3241. def on_pf_color_entry(self):
  3242. self.defaults['global_plot_fill'] = self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  3243. self.defaults['global_plot_fill'][7:9]
  3244. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  3245. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  3246. def on_pf_color_button(self):
  3247. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  3248. c_dialog = QtWidgets.QColorDialog()
  3249. plot_fill_color = c_dialog.getColor(initial=current_color)
  3250. if plot_fill_color.isValid() is False:
  3251. return
  3252. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  3253. "background-color:%s" % str(plot_fill_color.name()))
  3254. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  3255. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  3256. self.defaults['global_plot_fill'] = new_val
  3257. def on_pf_color_spinner(self):
  3258. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  3259. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  3260. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  3261. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3262. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  3263. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3264. def on_pf_color_slider(self):
  3265. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  3266. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  3267. def on_pl_color_entry(self):
  3268. self.defaults['global_plot_line'] = self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  3269. self.defaults['global_plot_line'][7:9]
  3270. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  3271. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  3272. def on_pl_color_button(self):
  3273. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  3274. # print(current_color)
  3275. c_dialog = QtWidgets.QColorDialog()
  3276. plot_line_color = c_dialog.getColor(initial=current_color)
  3277. if plot_line_color.isValid() is False:
  3278. return
  3279. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  3280. "background-color:%s" % str(plot_line_color.name()))
  3281. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  3282. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  3283. self.defaults['global_plot_line'] = new_val_line
  3284. # Setting selection colors (left - right) handlers
  3285. def on_sf_color_entry(self):
  3286. self.defaults['global_sel_fill'] = self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  3287. self.defaults['global_sel_fill'][7:9]
  3288. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  3289. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  3290. def on_sf_color_button(self):
  3291. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  3292. c_dialog = QtWidgets.QColorDialog()
  3293. plot_fill_color = c_dialog.getColor(initial=current_color)
  3294. if plot_fill_color.isValid() is False:
  3295. return
  3296. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  3297. "background-color:%s" % str(plot_fill_color.name()))
  3298. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  3299. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  3300. self.defaults['global_sel_fill'] = new_val
  3301. def on_sf_color_spinner(self):
  3302. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  3303. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  3304. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  3305. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3306. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  3307. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3308. def on_sf_color_slider(self):
  3309. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  3310. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  3311. def on_sl_color_entry(self):
  3312. self.defaults['global_sel_line'] = self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  3313. self.defaults['global_sel_line'][7:9]
  3314. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  3315. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  3316. def on_sl_color_button(self):
  3317. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  3318. c_dialog = QtWidgets.QColorDialog()
  3319. plot_line_color = c_dialog.getColor(initial=current_color)
  3320. if plot_line_color.isValid() is False:
  3321. return
  3322. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  3323. "background-color:%s" % str(plot_line_color.name()))
  3324. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  3325. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  3326. self.defaults['global_sel_line'] = new_val_line
  3327. # Setting selection colors (right - left) handlers
  3328. def on_alt_sf_color_entry(self):
  3329. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  3330. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  3331. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  3332. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  3333. def on_alt_sf_color_button(self):
  3334. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  3335. c_dialog = QtWidgets.QColorDialog()
  3336. plot_fill_color = c_dialog.getColor(initial=current_color)
  3337. if plot_fill_color.isValid() is False:
  3338. return
  3339. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  3340. "background-color:%s" % str(plot_fill_color.name()))
  3341. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  3342. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  3343. self.defaults['global_alt_sel_fill'] = new_val
  3344. def on_alt_sf_color_spinner(self):
  3345. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  3346. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  3347. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  3348. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3349. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  3350. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3351. def on_alt_sf_color_slider(self):
  3352. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  3353. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  3354. def on_alt_sl_color_entry(self):
  3355. self.defaults['global_alt_sel_line'] = self.ui.general_defaults_form.general_gui_group \
  3356. .alt_sl_color_entry.get_value()[:7] + self.defaults['global_alt_sel_line'][7:9]
  3357. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  3358. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  3359. def on_alt_sl_color_button(self):
  3360. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  3361. c_dialog = QtWidgets.QColorDialog()
  3362. plot_line_color = c_dialog.getColor(initial=current_color)
  3363. if plot_line_color.isValid() is False:
  3364. return
  3365. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  3366. "background-color:%s" % str(plot_line_color.name()))
  3367. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  3368. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  3369. self.defaults['global_alt_sel_line'] = new_val_line
  3370. # Setting Editor colors
  3371. def on_draw_color_entry(self):
  3372. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  3373. .draw_color_entry.get_value()
  3374. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  3375. "background-color:%s" % str(self.defaults['global_draw_color']))
  3376. def on_draw_color_button(self):
  3377. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  3378. c_dialog = QtWidgets.QColorDialog()
  3379. draw_color = c_dialog.getColor(initial=current_color)
  3380. if draw_color.isValid() is False:
  3381. return
  3382. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  3383. "background-color:%s" % str(draw_color.name()))
  3384. new_val = str(draw_color.name())
  3385. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  3386. self.defaults['global_draw_color'] = new_val
  3387. def on_sel_draw_color_entry(self):
  3388. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  3389. .sel_draw_color_entry.get_value()
  3390. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3391. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  3392. def on_sel_draw_color_button(self):
  3393. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  3394. c_dialog = QtWidgets.QColorDialog()
  3395. sel_draw_color = c_dialog.getColor(initial=current_color)
  3396. if sel_draw_color.isValid() is False:
  3397. return
  3398. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3399. "background-color:%s" % str(sel_draw_color.name()))
  3400. new_val_sel = str(sel_draw_color.name())
  3401. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  3402. self.defaults['global_sel_draw_color'] = new_val_sel
  3403. def on_proj_color_entry(self):
  3404. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  3405. .proj_color_entry.get_value()
  3406. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  3407. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  3408. def on_proj_color_button(self):
  3409. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  3410. c_dialog = QtWidgets.QColorDialog()
  3411. proj_color = c_dialog.getColor(initial=current_color)
  3412. if proj_color.isValid() is False:
  3413. return
  3414. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  3415. "background-color:%s" % str(proj_color.name()))
  3416. new_val_sel = str(proj_color.name())
  3417. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  3418. self.defaults['global_proj_item_color'] = new_val_sel
  3419. def on_proj_color_dis_entry(self):
  3420. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  3421. .proj_color_dis_entry.get_value()
  3422. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  3423. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  3424. def on_proj_color_dis_button(self):
  3425. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  3426. c_dialog = QtWidgets.QColorDialog()
  3427. proj_color = c_dialog.getColor(initial=current_color)
  3428. if proj_color.isValid() is False:
  3429. return
  3430. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  3431. "background-color:%s" % str(proj_color.name()))
  3432. new_val_sel = str(proj_color.name())
  3433. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  3434. self.defaults['global_proj_item_dis_color'] = new_val_sel
  3435. def on_deselect_all(self):
  3436. self.collection.set_all_inactive()
  3437. self.delete_selection_shape()
  3438. def on_workspace_modified(self):
  3439. self.save_defaults(silent=True)
  3440. self.plotcanvas.draw_workspace()
  3441. def on_workspace(self):
  3442. self.report_usage("on_workspace()")
  3443. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3444. self.plotcanvas.restore_workspace()
  3445. else:
  3446. self.plotcanvas.delete_workspace()
  3447. self.save_defaults(silent=True)
  3448. def on_workspace_menu(self):
  3449. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3450. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  3451. else:
  3452. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  3453. self.on_workspace()
  3454. def on_layout(self, index=None, lay=None):
  3455. self.report_usage("on_layout()")
  3456. if lay:
  3457. current_layout = lay
  3458. else:
  3459. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  3460. settings = QSettings("Open Source", "FlatCAM")
  3461. settings.setValue('layout', current_layout)
  3462. # This will write the setting to the platform specific storage.
  3463. del settings
  3464. # first remove the toolbars:
  3465. try:
  3466. self.ui.removeToolBar(self.ui.toolbarfile)
  3467. self.ui.removeToolBar(self.ui.toolbargeo)
  3468. self.ui.removeToolBar(self.ui.toolbarview)
  3469. self.ui.removeToolBar(self.ui.toolbarshell)
  3470. self.ui.removeToolBar(self.ui.toolbartools)
  3471. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  3472. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  3473. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  3474. self.ui.removeToolBar(self.ui.snap_toolbar)
  3475. self.ui.removeToolBar(self.ui.toolbarshell)
  3476. except:
  3477. pass
  3478. if current_layout == 'standard':
  3479. ### TOOLBAR INSTALLATION ###
  3480. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3481. self.ui.toolbarfile.setObjectName('File_TB')
  3482. self.ui.addToolBar(self.ui.toolbarfile)
  3483. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3484. self.ui.toolbargeo.setObjectName('Edit_TB')
  3485. self.ui.addToolBar(self.ui.toolbargeo)
  3486. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3487. self.ui.toolbarview.setObjectName('View_TB')
  3488. self.ui.addToolBar(self.ui.toolbarview)
  3489. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3490. self.ui.toolbarshell.setObjectName('Shell_TB')
  3491. self.ui.addToolBar(self.ui.toolbarshell)
  3492. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3493. self.ui.toolbartools.setObjectName('Tools_TB')
  3494. self.ui.addToolBar(self.ui.toolbartools)
  3495. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3496. self.ui.exc_edit_toolbar.setVisible(False)
  3497. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3498. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  3499. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3500. self.ui.geo_edit_toolbar.setVisible(False)
  3501. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3502. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  3503. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  3504. self.ui.grb_edit_toolbar.setVisible(False)
  3505. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  3506. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  3507. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3508. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3509. # self.ui.snap_toolbar.setMaximumHeight(30)
  3510. self.ui.addToolBar(self.ui.snap_toolbar)
  3511. self.ui.corner_snap_btn.setVisible(False)
  3512. self.ui.snap_magnet.setVisible(False)
  3513. elif current_layout == 'compact':
  3514. ### TOOLBAR INSTALLATION ###
  3515. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3516. self.ui.toolbarfile.setObjectName('File_TB')
  3517. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  3518. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3519. self.ui.toolbargeo.setObjectName('Edit_TB')
  3520. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  3521. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3522. self.ui.toolbarview.setObjectName('View_TB')
  3523. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  3524. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3525. self.ui.toolbarshell.setObjectName('Shell_TB')
  3526. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  3527. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3528. self.ui.toolbartools.setObjectName('Tools_TB')
  3529. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  3530. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3531. # self.ui.geo_edit_toolbar.setVisible(False)
  3532. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3533. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  3534. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  3535. # self.ui.grb_edit_toolbar.setVisible(False)
  3536. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  3537. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  3538. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3539. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3540. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  3541. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3542. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3543. self.ui.snap_toolbar.setMaximumHeight(30)
  3544. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  3545. self.ui.corner_snap_btn.setVisible(True)
  3546. self.ui.snap_magnet.setVisible(True)
  3547. # add all the actions to the toolbars
  3548. self.ui.populate_toolbars()
  3549. # reconnect all the signals to the toolbar actions
  3550. self.connect_toolbar_signals()
  3551. self.ui.grid_snap_btn.setChecked(True)
  3552. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  3553. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  3554. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  3555. self.ui.grid_gap_link_cb.setChecked(True)
  3556. def on_cnc_custom_parameters(self, signal_text):
  3557. if signal_text == 'Parameters':
  3558. return
  3559. else:
  3560. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  3561. def on_save_button(self):
  3562. self.save_defaults(silent=False)
  3563. # load the defaults so they are updated into the app
  3564. self.load_defaults(filename='current_defaults')
  3565. # Re-fresh project options
  3566. self.on_options_app2project()
  3567. def handlePrint(self):
  3568. self.report_usage("handlePrint()")
  3569. dialog = QtPrintSupport.QPrintDialog()
  3570. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  3571. self.ui.code_editor.document().print_(dialog.printer())
  3572. def handlePreview(self):
  3573. self.report_usage("handlePreview()")
  3574. dialog = QtPrintSupport.QPrintPreviewDialog()
  3575. dialog.paintRequested.connect(self.ui.code_editor.print_)
  3576. dialog.exec_()
  3577. def handleTextChanged(self):
  3578. # enable = not self.ui.code_editor.document().isEmpty()
  3579. # self.ui.buttonPrint.setEnabled(enable)
  3580. # self.ui.buttonPreview.setEnabled(enable)
  3581. pass
  3582. def handleOpen(self, filt=None):
  3583. self.report_usage("handleOpen()")
  3584. if filt:
  3585. _filter_ = filt
  3586. else:
  3587. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  3588. "All Files (*.*)"
  3589. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  3590. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  3591. if path:
  3592. file = QtCore.QFile(path)
  3593. if file.open(QtCore.QIODevice.ReadOnly):
  3594. stream = QtCore.QTextStream(file)
  3595. self.gcode_edited = stream.readAll()
  3596. self.ui.code_editor.setPlainText(self.gcode_edited)
  3597. file.close()
  3598. def handleSaveGCode(self,name=None, filt=None):
  3599. self.report_usage("handleSaveGCode()")
  3600. if filt:
  3601. _filter_ = filt
  3602. else:
  3603. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  3604. "All Files (*.*)"
  3605. if name:
  3606. obj_name = name
  3607. else:
  3608. try:
  3609. obj_name = self.collection.get_active().options['name']
  3610. except AttributeError:
  3611. obj_name = 'file'
  3612. if filt is None:
  3613. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  3614. try:
  3615. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  3616. caption=_("Export G-Code ..."),
  3617. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  3618. filter=_filter_
  3619. )[0])
  3620. except TypeError:
  3621. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  3622. if filename == "":
  3623. self.inform.emit(_("[WARNING_NOTCL] Export Code cancelled."))
  3624. return
  3625. else:
  3626. try:
  3627. my_gcode = self.ui.code_editor.toPlainText()
  3628. with open(filename, 'w') as f:
  3629. for line in my_gcode:
  3630. f.write(line)
  3631. except FileNotFoundError:
  3632. self.inform.emit(_("[WARNING] No such file or directory"))
  3633. return
  3634. # Just for adding it to the recent files list.
  3635. if self.defaults["global_open_style"] is False:
  3636. self.file_opened.emit("cncjob", filename)
  3637. self.file_saved.emit("cncjob", filename)
  3638. self.inform.emit(_("Saved to: %s") % filename)
  3639. def handleFindGCode(self):
  3640. self.report_usage("handleFindGCode()")
  3641. flags = QtGui.QTextDocument.FindCaseSensitively
  3642. text_to_be_found = self.ui.entryFind.get_value()
  3643. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  3644. if r is False:
  3645. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3646. def handleReplaceGCode(self):
  3647. self.report_usage("handleReplaceGCode()")
  3648. old = self.ui.entryFind.get_value()
  3649. new = self.ui.entryReplace.get_value()
  3650. if self.ui.sel_all_cb.isChecked():
  3651. while True:
  3652. cursor = self.ui.code_editor.textCursor()
  3653. cursor.beginEditBlock()
  3654. flags = QtGui.QTextDocument.FindCaseSensitively
  3655. # self.ui.editor is the QPlainTextEdit
  3656. r = self.ui.code_editor.find(str(old), flags)
  3657. if r:
  3658. qc = self.ui.code_editor.textCursor()
  3659. if qc.hasSelection():
  3660. qc.insertText(new)
  3661. else:
  3662. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3663. break
  3664. # Mark end of undo block
  3665. cursor.endEditBlock()
  3666. else:
  3667. cursor = self.ui.code_editor.textCursor()
  3668. cursor.beginEditBlock()
  3669. qc = self.ui.code_editor.textCursor()
  3670. if qc.hasSelection():
  3671. qc.insertText(new)
  3672. # Mark end of undo block
  3673. cursor.endEditBlock()
  3674. def on_tool_add_keypress(self):
  3675. ## Current application units in Upper Case
  3676. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3677. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3678. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3679. if notebook_widget_name == 'selected_tab':
  3680. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3681. # Tool add works for Geometry only if Advanced is True in Preferences
  3682. if self.defaults["global_app_level"] == 'a':
  3683. tool_add_popup = FCInputDialog(title="New Tool ...",
  3684. text='Enter a Tool Diameter:',
  3685. min=0.0000, max=99.9999, decimals=4)
  3686. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3687. val, ok = tool_add_popup.get_value()
  3688. if ok:
  3689. if float(val) == 0:
  3690. self.inform.emit(
  3691. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3692. return
  3693. self.collection.get_active().on_tool_add(dia=float(val))
  3694. else:
  3695. self.inform.emit(
  3696. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3697. else:
  3698. msgbox = QtWidgets.QMessageBox()
  3699. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3700. "Go to Preferences -> General - Show Advanced Options."))
  3701. msgbox.setWindowTitle("Tool adding ...")
  3702. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  3703. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3704. msgbox.setDefaultButton(bt_ok)
  3705. msgbox.exec_()
  3706. # work only if the notebook tab on focus is the Tools_Tab
  3707. if notebook_widget_name == 'tool_tab':
  3708. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3709. tool_add_popup = FCInputDialog(title="New Tool ...",
  3710. text='Enter a Tool Diameter:',
  3711. min=0.0000, max=99.9999, decimals=4)
  3712. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3713. val, ok = tool_add_popup.get_value()
  3714. # and only if the tool is NCC Tool
  3715. if tool_widget == self.ncclear_tool.toolName:
  3716. if ok:
  3717. if float(val) == 0:
  3718. self.inform.emit(
  3719. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3720. return
  3721. self.ncclear_tool.on_tool_add(dia=float(val))
  3722. else:
  3723. self.inform.emit(
  3724. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3725. # and only if the tool is Paint Area Tool
  3726. elif tool_widget == self.paint_tool.toolName:
  3727. if ok:
  3728. if float(val) == 0:
  3729. self.inform.emit(
  3730. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3731. return
  3732. self.paint_tool.on_tool_add(dia=float(val))
  3733. else:
  3734. self.inform.emit(
  3735. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3736. # and only if the tool is Solder Paste Dispensing Tool
  3737. elif tool_widget == self.paste_tool.toolName:
  3738. if ok:
  3739. if float(val) == 0:
  3740. self.inform.emit(
  3741. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3742. return
  3743. self.paste_tool.on_tool_add(dia=float(val))
  3744. else:
  3745. self.inform.emit(
  3746. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3747. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3748. # See description bellow.
  3749. def on_delete_keypress(self):
  3750. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3751. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3752. if notebook_widget_name == 'selected_tab':
  3753. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3754. self.collection.get_active().on_tool_delete()
  3755. # work only if the notebook tab on focus is the Tools_Tab
  3756. elif notebook_widget_name == 'tool_tab':
  3757. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3758. # and only if the tool is NCC Tool
  3759. if tool_widget == self.ncclear_tool.toolName:
  3760. self.ncclear_tool.on_tool_delete()
  3761. # and only if the tool is Paint Tool
  3762. elif tool_widget == self.paint_tool.toolName:
  3763. self.paint_tool.on_tool_delete()
  3764. # and only if the tool is Solder Paste Dispensing Tool
  3765. elif tool_widget == self.paste_tool.toolName:
  3766. self.paste_tool.on_tool_delete()
  3767. else:
  3768. self.on_delete()
  3769. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3770. # some screens you have to be careful where you hover with your mouse.
  3771. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3772. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3773. # Complicated, I know :)
  3774. def on_delete(self):
  3775. """
  3776. Delete the currently selected FlatCAMObjs.
  3777. :return: None
  3778. """
  3779. self.report_usage("on_delete()")
  3780. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3781. # a geometry object before we update it.
  3782. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  3783. if self.collection.get_active():
  3784. self.log.debug("on_delete()")
  3785. self.report_usage("on_delete")
  3786. while (self.collection.get_active()):
  3787. obj_active = self.collection.get_active()
  3788. # if the deleted object is FlatCAMGerber then make sure to delete the possbile mark shapes
  3789. if isinstance(obj_active, FlatCAMGerber):
  3790. for el in obj_active.mark_shapes:
  3791. obj_active.mark_shapes[el].clear(update=True)
  3792. obj_active.mark_shapes[el].enabled = False
  3793. obj_active.mark_shapes[el] = None
  3794. self.delete_first_selected()
  3795. self.inform.emit(_("Object(s) deleted ..."))
  3796. # make sure that the selection shape is deleted, too
  3797. self.delete_selection_shape()
  3798. else:
  3799. self.inform.emit(_("Failed. No object(s) selected..."))
  3800. else:
  3801. self.inform.emit(_("Save the work in Editor and try again ..."))
  3802. def on_set_origin(self):
  3803. """
  3804. Set the origin to the left mouse click position
  3805. :return: None
  3806. """
  3807. #display the message for the user
  3808. #and ask him to click on the desired position
  3809. self.report_usage("on_set_origin()")
  3810. self.inform.emit(_('Click to set the origin ...'))
  3811. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  3812. def on_jump_to(self, custom_location=None, fit_center=True):
  3813. """
  3814. Jump to a location by setting the mouse cursor location
  3815. :return:
  3816. """
  3817. self.report_usage("on_jump_to()")
  3818. if not custom_location:
  3819. dia_box = Dialog_box(title=_("Jump to ..."),
  3820. label=_("Enter the coordinates in format X,Y:"),
  3821. icon=QtGui.QIcon('share/jump_to16.png'))
  3822. if dia_box.ok is True:
  3823. try:
  3824. location = eval(dia_box.location)
  3825. if not isinstance(location, tuple):
  3826. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3827. return
  3828. except:
  3829. return
  3830. else:
  3831. return
  3832. else:
  3833. location = custom_location
  3834. if fit_center:
  3835. self.plotcanvas.fit_center(loc=location)
  3836. cursor = QtGui.QCursor()
  3837. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3838. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  3839. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  3840. self.inform.emit(_("[success] Done."))
  3841. def on_copy_object(self):
  3842. self.report_usage("on_copy_object()")
  3843. def initialize(obj_init, app):
  3844. obj_init.solid_geometry = obj.solid_geometry
  3845. try:
  3846. obj_init.follow_geometry = obj.follow_geometry
  3847. except:
  3848. pass
  3849. try:
  3850. obj_init.apertures = obj.apertures
  3851. except:
  3852. pass
  3853. try:
  3854. if obj.tools:
  3855. obj_init.tools = obj.tools
  3856. except Exception as e:
  3857. log.debug("on_copy_object() --> %s" % str(e))
  3858. def initialize_excellon(obj_init, app):
  3859. obj_init.tools = obj.tools
  3860. # drills are offset, so they need to be deep copied
  3861. obj_init.drills = deepcopy(obj.drills)
  3862. # slots are offset, so they need to be deep copied
  3863. obj_init.slots = deepcopy(obj.slots)
  3864. obj_init.create_geometry()
  3865. for obj in self.collection.get_selected():
  3866. obj_name = obj.options["name"]
  3867. try:
  3868. if isinstance(obj, FlatCAMExcellon):
  3869. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  3870. elif isinstance(obj,FlatCAMGerber):
  3871. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  3872. elif isinstance(obj,FlatCAMGeometry):
  3873. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  3874. except Exception as e:
  3875. return "Operation failed: %s" % str(e)
  3876. def on_copy_object2(self, custom_name):
  3877. def initialize_geometry(obj_init, app):
  3878. obj_init.solid_geometry = obj.solid_geometry
  3879. try:
  3880. obj_init.follow_geometry = obj.follow_geometry
  3881. except:
  3882. pass
  3883. try:
  3884. obj_init.apertures = obj.apertures
  3885. except:
  3886. pass
  3887. try:
  3888. if obj.tools:
  3889. obj_init.tools = obj.tools
  3890. except Exception as e:
  3891. log.debug("on_copy_object2() --> %s" % str(e))
  3892. def initialize_gerber(obj_init, app):
  3893. obj_init.solid_geometry = obj.solid_geometry
  3894. obj_init.apertures = deepcopy(obj.apertures)
  3895. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  3896. def initialize_excellon(obj_init, app):
  3897. obj_init.tools = obj.tools
  3898. # drills are offset, so they need to be deep copied
  3899. obj_init.drills = deepcopy(obj.drills)
  3900. # slots are offset, so they need to be deep copied
  3901. obj_init.slots = deepcopy(obj.slots)
  3902. obj_init.create_geometry()
  3903. for obj in self.collection.get_selected():
  3904. obj_name = obj.options["name"]
  3905. try:
  3906. if isinstance(obj, FlatCAMExcellon):
  3907. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  3908. elif isinstance(obj,FlatCAMGerber):
  3909. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  3910. elif isinstance(obj,FlatCAMGeometry):
  3911. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  3912. except Exception as e:
  3913. return "Operation failed: %s" % str(e)
  3914. def on_rename_object(self, text):
  3915. self.report_usage("on_rename_object()")
  3916. named_obj = self.collection.get_active()
  3917. for obj in named_obj:
  3918. if obj is list:
  3919. self.on_rename_object(text)
  3920. else:
  3921. try:
  3922. obj.options['name'] = text
  3923. except:
  3924. log.warning("Could not rename the object in the list")
  3925. def convert_any2geo(self):
  3926. self.report_usage("convert_any2geo()")
  3927. def initialize(obj_init, app):
  3928. obj_init.solid_geometry = obj.solid_geometry
  3929. try:
  3930. obj_init.follow_geometry = obj.follow_geometry
  3931. except:
  3932. pass
  3933. try:
  3934. obj_init.apertures = obj.apertures
  3935. except:
  3936. pass
  3937. try:
  3938. if obj.tools:
  3939. obj_init.tools = obj.tools
  3940. except AttributeError:
  3941. pass
  3942. def initialize_excellon(obj_init, app):
  3943. # objs = self.collection.get_selected()
  3944. # FlatCAMGeometry.merge(objs, obj)
  3945. solid_geo = []
  3946. for tool in obj.tools:
  3947. for geo in obj.tools[tool]['solid_geometry']:
  3948. solid_geo.append(geo)
  3949. obj_init.solid_geometry = deepcopy(solid_geo)
  3950. if not self.collection.get_selected():
  3951. log.warning("App.convert_any2geo --> No object selected")
  3952. self.inform.emit(_("[WARNING_NOTCL] No object is selected. Select an object and try again."))
  3953. return
  3954. for obj in self.collection.get_selected():
  3955. obj_name = obj.options["name"]
  3956. try:
  3957. if isinstance(obj, FlatCAMExcellon):
  3958. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  3959. else:
  3960. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  3961. except Exception as e:
  3962. return "Operation failed: %s" % str(e)
  3963. def convert_any2gerber(self):
  3964. self.report_usage("convert_any2gerber()")
  3965. def initialize_geometry(obj_init, app):
  3966. apertures = {}
  3967. apid = 0
  3968. apertures[str(apid)] = {}
  3969. apertures[str(apid)]['geometry'] = []
  3970. for obj_orig in obj.solid_geometry:
  3971. new_elem = dict()
  3972. new_elem['solid'] = obj_orig
  3973. new_elem['follow'] = obj_orig.exterior
  3974. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  3975. apertures[str(apid)]['size'] = 0.0
  3976. apertures[str(apid)]['type'] = 'C'
  3977. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  3978. obj_init.apertures = deepcopy(apertures)
  3979. def initialize_excellon(obj_init, app):
  3980. apertures = {}
  3981. apid = 10
  3982. for tool in obj.tools:
  3983. apertures[str(apid)] = {}
  3984. apertures[str(apid)]['geometry'] = []
  3985. for geo in obj.tools[tool]['solid_geometry']:
  3986. new_el = dict()
  3987. new_el['solid'] = geo
  3988. new_el['follow'] = geo.exterior
  3989. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  3990. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  3991. apertures[str(apid)]['type'] = 'C'
  3992. apid += 1
  3993. # create solid_geometry
  3994. solid_geometry = []
  3995. for apid in apertures:
  3996. for geo_el in apertures[apid]['geometry']:
  3997. solid_geometry.append(geo_el['solid'])
  3998. solid_geometry = MultiPolygon(solid_geometry)
  3999. solid_geometry = solid_geometry.buffer(0.0000001)
  4000. obj_init.solid_geometry = deepcopy(solid_geometry)
  4001. obj_init.apertures = deepcopy(apertures)
  4002. # clear the working objects (perhaps not necessary due of Python GC)
  4003. apertures.clear()
  4004. if not self.collection.get_selected():
  4005. log.warning("App.convert_any2gerber --> No object selected")
  4006. self.inform.emit(_("[WARNING_NOTCL] No object is selected. Select an object and try again."))
  4007. return
  4008. for obj in self.collection.get_selected():
  4009. obj_name = obj.options["name"]
  4010. try:
  4011. if isinstance(obj, FlatCAMExcellon):
  4012. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4013. elif isinstance(obj, FlatCAMGeometry):
  4014. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4015. else:
  4016. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4017. except Exception as e:
  4018. return "Operation failed: %s" % str(e)
  4019. def on_set_zero_click(self, event):
  4020. #this function will be available only for mouse left click
  4021. pos =[]
  4022. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4023. if event.button == 1:
  4024. if self.grid_status() == True:
  4025. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4026. else:
  4027. pos = pos_canvas
  4028. x = 0 - pos[0]
  4029. y = 0 - pos[1]
  4030. for obj in self.collection.get_list():
  4031. obj.offset((x,y))
  4032. self.object_changed.emit(obj)
  4033. obj.plot()
  4034. # Update the object bounding box options
  4035. a, b, c, d = obj.bounds()
  4036. obj.options['xmin'] = a
  4037. obj.options['ymin'] = b
  4038. obj.options['xmax'] = c
  4039. obj.options['ymax'] = d
  4040. # self.plot_all(zoom=False)
  4041. self.inform.emit(_('[success] Origin set ...'))
  4042. self.plotcanvas.fit_view()
  4043. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  4044. self.should_we_save = True
  4045. def on_selectall(self):
  4046. self.report_usage("on_selectall()")
  4047. # delete the possible selection box around a possible selected object
  4048. self.delete_selection_shape()
  4049. for name in self.collection.get_names():
  4050. self.collection.set_active(name)
  4051. curr_sel_obj = self.collection.get_by_name(name)
  4052. # create the selection box around the selected object
  4053. if self.defaults['global_selection_shape'] is True:
  4054. self.draw_selection_shape(curr_sel_obj)
  4055. def on_preferences(self):
  4056. # add the tab if it was closed
  4057. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4058. # delete the absolute and relative position and messages in the infobar
  4059. self.ui.position_label.setText("")
  4060. self.ui.rel_position_label.setText("")
  4061. # Switch plot_area to preferences page
  4062. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4063. self.ui.show()
  4064. def on_flipy(self):
  4065. self.report_usage("on_flipy()")
  4066. obj_list = self.collection.get_selected()
  4067. xminlist = []
  4068. yminlist = []
  4069. xmaxlist = []
  4070. ymaxlist = []
  4071. if not obj_list:
  4072. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on Y axis."))
  4073. else:
  4074. try:
  4075. # first get a bounding box to fit all
  4076. for obj in obj_list:
  4077. xmin, ymin, xmax, ymax = obj.bounds()
  4078. xminlist.append(xmin)
  4079. yminlist.append(ymin)
  4080. xmaxlist.append(xmax)
  4081. ymaxlist.append(ymax)
  4082. # get the minimum x,y and maximum x,y for all objects selected
  4083. xminimal = min(xminlist)
  4084. yminimal = min(yminlist)
  4085. xmaximal = max(xmaxlist)
  4086. ymaximal = max(ymaxlist)
  4087. px = 0.5 * (xminimal + xmaximal)
  4088. py = 0.5 * (yminimal + ymaximal)
  4089. # execute mirroring
  4090. for obj in obj_list:
  4091. obj.mirror('X', [px, py])
  4092. obj.plot()
  4093. self.object_changed.emit(obj)
  4094. self.inform.emit(_("[success] Flip on Y axis done."))
  4095. except Exception as e:
  4096. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  4097. return
  4098. def on_flipx(self):
  4099. self.report_usage("on_flipx()")
  4100. obj_list = self.collection.get_selected()
  4101. xminlist = []
  4102. yminlist = []
  4103. xmaxlist = []
  4104. ymaxlist = []
  4105. if not obj_list:
  4106. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on X axis."))
  4107. else:
  4108. try:
  4109. # first get a bounding box to fit all
  4110. for obj in obj_list:
  4111. xmin, ymin, xmax, ymax = obj.bounds()
  4112. xminlist.append(xmin)
  4113. yminlist.append(ymin)
  4114. xmaxlist.append(xmax)
  4115. ymaxlist.append(ymax)
  4116. # get the minimum x,y and maximum x,y for all objects selected
  4117. xminimal = min(xminlist)
  4118. yminimal = min(yminlist)
  4119. xmaximal = max(xmaxlist)
  4120. ymaximal = max(ymaxlist)
  4121. px = 0.5 * (xminimal + xmaximal)
  4122. py = 0.5 * (yminimal + ymaximal)
  4123. # execute mirroring
  4124. for obj in obj_list:
  4125. obj.mirror('Y', [px, py])
  4126. obj.plot()
  4127. self.object_changed.emit(obj)
  4128. self.inform.emit(_("[success] Flip on X axis done."))
  4129. except Exception as e:
  4130. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  4131. return
  4132. def on_rotate(self, silent=False, preset=None):
  4133. self.report_usage("on_rotate()")
  4134. obj_list = self.collection.get_selected()
  4135. xminlist = []
  4136. yminlist = []
  4137. xmaxlist = []
  4138. ymaxlist = []
  4139. if not obj_list:
  4140. self.inform.emit(_("[WARNING_NOTCL] No object selected to Rotate."))
  4141. else:
  4142. if silent is False:
  4143. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4144. min=-360, max=360, decimals=4,
  4145. init_val=float(self.defaults['tools_transform_rotate']))
  4146. num, ok = rotatebox.get_value()
  4147. else:
  4148. num = preset
  4149. ok = True
  4150. if ok:
  4151. try:
  4152. # first get a bounding box to fit all
  4153. for obj in obj_list:
  4154. xmin, ymin, xmax, ymax = obj.bounds()
  4155. xminlist.append(xmin)
  4156. yminlist.append(ymin)
  4157. xmaxlist.append(xmax)
  4158. ymaxlist.append(ymax)
  4159. # get the minimum x,y and maximum x,y for all objects selected
  4160. xminimal = min(xminlist)
  4161. yminimal = min(yminlist)
  4162. xmaximal = max(xmaxlist)
  4163. ymaximal = max(ymaxlist)
  4164. px = 0.5 * (xminimal + xmaximal)
  4165. py = 0.5 * (yminimal + ymaximal)
  4166. for sel_obj in obj_list:
  4167. sel_obj.rotate(-float(num), point=(px, py))
  4168. sel_obj.plot()
  4169. self.object_changed.emit(sel_obj)
  4170. self.inform.emit(_("[success] Rotation done."))
  4171. except Exception as e:
  4172. self.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  4173. return
  4174. def on_skewx(self):
  4175. self.report_usage("on_skewx()")
  4176. obj_list = self.collection.get_selected()
  4177. xminlist = []
  4178. yminlist = []
  4179. if not obj_list:
  4180. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on X axis."))
  4181. else:
  4182. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4183. min=-360, max=360, decimals=4,
  4184. init_val=float(self.defaults['tools_transform_skew_x']))
  4185. num, ok = skewxbox.get_value()
  4186. if ok:
  4187. # first get a bounding box to fit all
  4188. for obj in obj_list:
  4189. xmin, ymin, xmax, ymax = obj.bounds()
  4190. xminlist.append(xmin)
  4191. yminlist.append(ymin)
  4192. # get the minimum x,y and maximum x,y for all objects selected
  4193. xminimal = min(xminlist)
  4194. yminimal = min(yminlist)
  4195. for obj in obj_list:
  4196. obj.skew(num, 0, point=(xminimal, yminimal))
  4197. obj.plot()
  4198. self.object_changed.emit(obj)
  4199. self.inform.emit(_("[success] Skew on X axis done."))
  4200. def on_skewy(self):
  4201. self.report_usage("on_skewy()")
  4202. obj_list = self.collection.get_selected()
  4203. xminlist = []
  4204. yminlist = []
  4205. if not obj_list:
  4206. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on Y axis."))
  4207. else:
  4208. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4209. min=-360, max=360, decimals=4,
  4210. init_val=float(self.defaults['tools_transform_skew_y']))
  4211. num, ok = skewybox.get_value()
  4212. if ok:
  4213. # first get a bounding box to fit all
  4214. for obj in obj_list:
  4215. xmin, ymin, xmax, ymax = obj.bounds()
  4216. xminlist.append(xmin)
  4217. yminlist.append(ymin)
  4218. # get the minimum x,y and maximum x,y for all objects selected
  4219. xminimal = min(xminlist)
  4220. yminimal = min(yminlist)
  4221. for obj in obj_list:
  4222. obj.skew(0, num, point=(xminimal, yminimal))
  4223. obj.plot()
  4224. self.object_changed.emit(obj)
  4225. self.inform.emit(_("[success] Skew on Y axis done."))
  4226. def delete_first_selected(self):
  4227. # Keep this for later
  4228. try:
  4229. name = self.collection.get_active().options["name"]
  4230. except AttributeError:
  4231. self.log.debug("Nothing selected for deletion")
  4232. return
  4233. # Remove plot
  4234. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4235. # self.plotcanvas.auto_adjust_axes()
  4236. # Clear form
  4237. self.setup_component_editor()
  4238. # Remove from dictionary
  4239. self.collection.delete_active()
  4240. self.inform.emit("Object deleted: %s" % name)
  4241. def on_plots_updated(self):
  4242. """
  4243. Callback used to report when the plots have changed.
  4244. Adjust axes and zooms to fit.
  4245. :return: None
  4246. """
  4247. # self.plotcanvas.auto_adjust_axes()
  4248. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  4249. self.on_zoom_fit(None)
  4250. self.collection.update_view()
  4251. # TODO: Rework toolbar 'clear', 'replot' functions
  4252. def on_toolbar_replot(self):
  4253. """
  4254. Callback for toolbar button. Re-plots all objects.
  4255. :return: None
  4256. """
  4257. self.report_usage("on_toolbar_replot")
  4258. self.log.debug("on_toolbar_replot()")
  4259. try:
  4260. self.collection.get_active().read_form()
  4261. except AttributeError:
  4262. self.log.debug("on_toolbar_replot(): AttributeError")
  4263. pass
  4264. self.plot_all()
  4265. def on_row_activated(self, index):
  4266. if index.isValid():
  4267. if index.internalPointer().parent_item != self.collection.root_item:
  4268. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4269. def grid_status(self):
  4270. if self.ui.grid_snap_btn.isChecked():
  4271. return 1
  4272. else:
  4273. return 0
  4274. def populate_cmenu_grids(self):
  4275. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4276. self.ui.cmenu_gridmenu.clear()
  4277. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4278. for grid in sorted_list:
  4279. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  4280. action.triggered.connect(self.set_grid)
  4281. self.ui.cmenu_gridmenu.addSeparator()
  4282. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  4283. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  4284. grid_add.triggered.connect(self.on_grid_add)
  4285. grid_delete.triggered.connect(self.on_grid_delete)
  4286. def set_grid(self):
  4287. self.ui.grid_gap_x_entry.setText(self.sender().text())
  4288. self.ui.grid_gap_y_entry.setText(self.sender().text())
  4289. def on_grid_add(self):
  4290. ## Current application units in lower Case
  4291. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4292. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4293. text=_('Enter a Grid Value:'),
  4294. min=0.0000, max=99.9999, decimals=4)
  4295. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  4296. val, ok = grid_add_popup.get_value()
  4297. if ok:
  4298. if float(val) == 0:
  4299. self.inform.emit(
  4300. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  4301. return
  4302. else:
  4303. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4304. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4305. self.inform.emit(
  4306. _("[success] New Grid added ..."))
  4307. else:
  4308. self.inform.emit(
  4309. _("[WARNING_NOTCL] Grid already exists ..."))
  4310. else:
  4311. self.inform.emit(
  4312. _("[WARNING_NOTCL] Adding New Grid cancelled ..."))
  4313. def on_grid_delete(self):
  4314. ## Current application units in lower Case
  4315. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4316. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4317. text='Enter a Grid Value:',
  4318. min=0.0000, max=99.9999, decimals=4)
  4319. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  4320. val, ok = grid_del_popup.get_value()
  4321. if ok:
  4322. if float(val) == 0:
  4323. self.inform.emit(
  4324. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  4325. return
  4326. else:
  4327. try:
  4328. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4329. except ValueError:
  4330. self.inform.emit(
  4331. _("[ERROR_NOTCL] Grid Value does not exist ..."))
  4332. return
  4333. self.inform.emit(
  4334. _("[success] Grid Value deleted ..."))
  4335. else:
  4336. self.inform.emit(
  4337. _("[WARNING_NOTCL] Delete Grid value cancelled ..."))
  4338. def on_shortcut_list(self):
  4339. self.report_usage("on_shortcut_list()")
  4340. # add the tab if it was closed
  4341. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, "Key Shortcut List")
  4342. # delete the absolute and relative position and messages in the infobar
  4343. self.ui.position_label.setText("")
  4344. self.ui.rel_position_label.setText("")
  4345. # Switch plot_area to preferences page
  4346. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4347. self.ui.show()
  4348. def on_select_tab(self, name):
  4349. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4350. if self.ui.splitter.sizes()[0] == 0:
  4351. self.ui.splitter.setSizes([1, 1])
  4352. else:
  4353. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4354. self.ui.splitter.setSizes([0, 1])
  4355. if name == 'project':
  4356. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4357. elif name == 'selected':
  4358. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4359. elif name == 'tool':
  4360. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4361. def on_copy_name(self):
  4362. self.report_usage("on_copy_name()")
  4363. obj = self.collection.get_active()
  4364. try:
  4365. name = obj.options["name"]
  4366. except AttributeError:
  4367. log.debug("on_copy_name() --> No object selected to copy it's name")
  4368. self.inform.emit(_("[WARNING_NOTCL] No object selected to copy it's name"))
  4369. return
  4370. self.clipboard.setText(name)
  4371. self.inform.emit(_("Name copied on clipboard ..."))
  4372. def on_mouse_click_over_plot(self, event):
  4373. """
  4374. Default actions are:
  4375. :param event: Contains information about the event, like which button
  4376. was clicked, the pixel coordinates and the axes coordinates.
  4377. :return: None
  4378. """
  4379. self.pos = []
  4380. # So it can receive key presses
  4381. self.plotcanvas.vispy_canvas.native.setFocus()
  4382. # Set the mouse button for panning
  4383. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  4384. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4385. if self.grid_status() == True:
  4386. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4387. self.app_cursor.enabled = True
  4388. else:
  4389. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4390. self.app_cursor.enabled = False
  4391. try:
  4392. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4393. if event.button == 1:
  4394. # Reset here the relative coordinates so there is a new reference on the click position
  4395. if self.rel_point1 is None:
  4396. self.rel_point1 = self.pos
  4397. else:
  4398. self.rel_point2 = copy(self.rel_point1)
  4399. self.rel_point1 = self.pos
  4400. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  4401. if modifiers == QtCore.Qt.ShiftModifier:
  4402. # do not auto open the Project Tab
  4403. self.click_noproject = True
  4404. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  4405. return
  4406. self.on_mouse_move_over_plot(event, origin_click=True)
  4407. except Exception as e:
  4408. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4409. def on_double_click_over_plot(self, event):
  4410. self.doubleclick = True
  4411. def on_mouse_move_over_plot(self, event, origin_click=None):
  4412. """
  4413. Callback for the mouse motion event over the plot.
  4414. :param event: Contains information about the event.
  4415. :param origin_click
  4416. :return: None
  4417. """
  4418. # So it can receive key presses
  4419. self.plotcanvas.vispy_canvas.native.setFocus()
  4420. self.pos_jump = event.pos
  4421. self.ui.popMenu.mouse_is_panning = False
  4422. if origin_click != True:
  4423. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4424. if event.button == 2 and event.is_dragging == 1:
  4425. self.ui.popMenu.mouse_is_panning = True
  4426. return
  4427. if self.rel_point1 is not None:
  4428. try: # May fail in case mouse not within axes
  4429. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4430. if self.grid_status():
  4431. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4432. self.app_cursor.enabled = True
  4433. # Update cursor
  4434. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  4435. else:
  4436. pos = (pos_canvas[0], pos_canvas[1])
  4437. self.app_cursor.enabled = False
  4438. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4439. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  4440. dx = pos[0] - self.rel_point1[0]
  4441. dy = pos[1] - self.rel_point1[1]
  4442. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4443. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4444. self.mouse = [pos[0], pos[1]]
  4445. # if the mouse is moved and the LMB is clicked then the action is a selection
  4446. if event.is_dragging == 1 and event.button == 1:
  4447. self.delete_selection_shape()
  4448. if dx < 0:
  4449. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4450. face_color=self.defaults['global_alt_sel_fill'])
  4451. self.selection_type = False
  4452. else:
  4453. self.draw_moving_selection_shape(self.pos, pos)
  4454. self.selection_type = True
  4455. # hover effect - enabled in Preferences -> General -> GUI Settings
  4456. if self.defaults['global_hover']:
  4457. for obj in self.collection.get_list():
  4458. try:
  4459. # select the object(s) only if it is enabled (plotted)
  4460. if obj.options['plot']:
  4461. if obj not in self.collection.get_selected():
  4462. poly_obj = Polygon(
  4463. [(obj.options['xmin'], obj.options['ymin']),
  4464. (obj.options['xmax'], obj.options['ymin']),
  4465. (obj.options['xmax'], obj.options['ymax']),
  4466. (obj.options['xmin'], obj.options['ymax'])]
  4467. )
  4468. if Point(pos).within(poly_obj):
  4469. if obj.isHovering is False:
  4470. obj.isHovering = True
  4471. obj.notHovering = True
  4472. # create the selection box around the selected object
  4473. self.draw_hover_shape(obj, color='#d1e0e0')
  4474. else:
  4475. if obj.notHovering is True:
  4476. obj.notHovering = False
  4477. obj.isHovering = False
  4478. self.delete_hover_shape()
  4479. except:
  4480. # the Exception here will happen if we try to select on screen and we have an
  4481. # newly (and empty) just created Geometry or Excellon object that do not have the
  4482. # xmin, xmax, ymin, ymax options.
  4483. # In this case poly_obj creation (see above) will fail
  4484. pass
  4485. except:
  4486. self.ui.position_label.setText("")
  4487. self.ui.rel_position_label.setText("")
  4488. self.mouse = None
  4489. def on_mouse_click_release_over_plot(self, event):
  4490. """
  4491. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  4492. and has been registered in ''self.__init__()''.
  4493. :param event: contains information about the event.
  4494. :return:
  4495. """
  4496. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4497. if self.grid_status():
  4498. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4499. else:
  4500. pos = (pos_canvas[0], pos_canvas[1])
  4501. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  4502. # canvas menu
  4503. try:
  4504. if event.button == 2: # right click
  4505. if self.ui.popMenu.mouse_is_panning is False:
  4506. self.cursor = QtGui.QCursor()
  4507. self.populate_cmenu_grids()
  4508. self.ui.popMenu.popup(self.cursor.pos())
  4509. except Exception as e:
  4510. log.warning("Error: %s" % str(e))
  4511. return
  4512. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  4513. # selection and then select a type of selection ("enclosing" or "touching")
  4514. try:
  4515. if event.button == 1: # left click
  4516. if self.doubleclick is True:
  4517. self.doubleclick = False
  4518. if self.collection.get_selected():
  4519. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4520. if self.ui.splitter.sizes()[0] == 0:
  4521. self.ui.splitter.setSizes([1, 1])
  4522. # delete the selection shape(S) as it may be in the way
  4523. self.delete_selection_shape()
  4524. self.delete_hover_shape()
  4525. else:
  4526. if self.selection_type is not None:
  4527. self.selection_area_handler(self.pos, pos, self.selection_type)
  4528. self.selection_type = None
  4529. else:
  4530. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4531. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will deselect,
  4532. # and if it's not selected then it will be selected
  4533. if modifiers == QtCore.Qt.ControlModifier:
  4534. # If there is no active command (self.command_active is None) then we check if we clicked on
  4535. # a object by checking the bounding limits against mouse click position
  4536. if self.command_active is None:
  4537. self.select_objects(key='CTRL')
  4538. self.delete_hover_shape()
  4539. else:
  4540. # If there is no active command (self.command_active is None) then we check if we clicked on a object by
  4541. # checking the bounding limits against mouse click position
  4542. if self.command_active is None:
  4543. self.select_objects()
  4544. self.delete_hover_shape()
  4545. except Exception as e:
  4546. log.warning("Error: %s" % str(e))
  4547. return
  4548. def selection_area_handler(self, start_pos, end_pos, sel_type):
  4549. """
  4550. :param start_pos: mouse position when the selection LMB click was done
  4551. :param end_pos: mouse position when the left mouse button is released
  4552. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4553. :return:
  4554. """
  4555. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4556. self.delete_selection_shape()
  4557. for obj in self.collection.get_list():
  4558. try:
  4559. # select the object(s) only if it is enabled (plotted)
  4560. if obj.options['plot']:
  4561. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  4562. (obj.options['xmax'], obj.options['ymin']),
  4563. (obj.options['xmax'], obj.options['ymax']),
  4564. (obj.options['xmin'], obj.options['ymax'])])
  4565. if sel_type is True:
  4566. if poly_obj.within(poly_selection):
  4567. # create the selection box around the selected object
  4568. if self.defaults['global_selection_shape'] is True:
  4569. self.draw_selection_shape(obj)
  4570. self.collection.set_active(obj.options['name'])
  4571. else:
  4572. if poly_selection.intersects(poly_obj):
  4573. # create the selection box around the selected object
  4574. if self.defaults['global_selection_shape'] is True:
  4575. self.draw_selection_shape(obj)
  4576. self.collection.set_active(obj.options['name'])
  4577. except:
  4578. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  4579. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  4580. # In this case poly_obj creation (see above) will fail
  4581. pass
  4582. def select_objects(self, key=None):
  4583. # list where we store the overlapped objects under our mouse left click position
  4584. objects_under_the_click_list = []
  4585. # Populate the list with the overlapped objects on the click position
  4586. curr_x, curr_y = self.pos
  4587. for obj in self.all_objects_list:
  4588. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  4589. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  4590. if obj.options['name'] not in objects_under_the_click_list:
  4591. if obj.options['plot']:
  4592. # add objects to the objects_under_the_click list only if the object is plotted
  4593. # (active and not disabled)
  4594. objects_under_the_click_list.append(obj.options['name'])
  4595. try:
  4596. # If there is no element in the overlapped objects list then make everyone inactive
  4597. # because we selected "nothing"
  4598. if not objects_under_the_click_list:
  4599. self.collection.set_all_inactive()
  4600. # delete the possible selection box around a possible selected object
  4601. self.delete_selection_shape()
  4602. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  4603. # only when working on App
  4604. if self.call_source == 'app':
  4605. if self.click_noproject is False:
  4606. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4607. else:
  4608. # restore auto open the Project Tab
  4609. self.click_noproject = False
  4610. # delete any text in the status bar, implicitly the last object name that was selected
  4611. self.inform.emit("")
  4612. else:
  4613. self.call_source = 'app'
  4614. else:
  4615. # case when there is only an object under the click and we toggle it
  4616. if len(objects_under_the_click_list) == 1:
  4617. if self.collection.get_active() is None :
  4618. self.collection.set_active(objects_under_the_click_list[0])
  4619. # create the selection box around the selected object
  4620. curr_sel_obj = self.collection.get_active()
  4621. if self.defaults['global_selection_shape'] is True:
  4622. self.draw_selection_shape(curr_sel_obj)
  4623. # self.inform.emit('[selected] %s: %s selected' %
  4624. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4625. if curr_sel_obj.kind == 'gerber':
  4626. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4627. color='green', name=str(curr_sel_obj.options['name'])))
  4628. elif curr_sel_obj.kind == 'excellon':
  4629. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4630. color='brown', name=str(curr_sel_obj.options['name'])))
  4631. elif curr_sel_obj.kind == 'cncjob':
  4632. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4633. color='blue', name=str(curr_sel_obj.options['name'])))
  4634. elif curr_sel_obj.kind == 'geometry':
  4635. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4636. color='red', name=str(curr_sel_obj.options['name'])))
  4637. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  4638. self.collection.set_all_inactive()
  4639. self.delete_selection_shape()
  4640. self.collection.set_active(objects_under_the_click_list[0])
  4641. # create the selection box around the selected object
  4642. curr_sel_obj = self.collection.get_active()
  4643. if self.defaults['global_selection_shape'] is True:
  4644. self.draw_selection_shape(curr_sel_obj)
  4645. # self.inform.emit('[selected] %s: %s selected' %
  4646. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4647. if curr_sel_obj.kind == 'gerber':
  4648. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4649. color='green', name=str(curr_sel_obj.options['name'])))
  4650. elif curr_sel_obj.kind == 'excellon':
  4651. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4652. color='brown', name=str(curr_sel_obj.options['name'])))
  4653. elif curr_sel_obj.kind == 'cncjob':
  4654. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4655. color='blue', name=str(curr_sel_obj.options['name'])))
  4656. elif curr_sel_obj.kind == 'geometry':
  4657. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4658. color='red', name=str(curr_sel_obj.options['name'])))
  4659. else:
  4660. self.collection.set_all_inactive()
  4661. self.delete_selection_shape()
  4662. if self.call_source == 'app':
  4663. # delete any text in the status bar, implicitly the last object name that was selected
  4664. self.inform.emit("")
  4665. else:
  4666. self.call_source = 'app'
  4667. else:
  4668. # If there is no selected object
  4669. # make active the first element of the overlapped objects list
  4670. if self.collection.get_active() is None:
  4671. self.collection.set_active(objects_under_the_click_list[0])
  4672. name_sel_obj = self.collection.get_active().options['name']
  4673. # In case that there is a selected object but it is not in the overlapped object list
  4674. # make that object inactive and activate the first element in the overlapped object list
  4675. if name_sel_obj not in objects_under_the_click_list:
  4676. self.collection.set_inactive(name_sel_obj)
  4677. name_sel_obj = objects_under_the_click_list[0]
  4678. self.collection.set_active(name_sel_obj)
  4679. else:
  4680. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  4681. self.collection.set_all_inactive()
  4682. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  4683. len(objects_under_the_click_list)])
  4684. curr_sel_obj = self.collection.get_active()
  4685. # delete the possible selection box around a possible selected object
  4686. self.delete_selection_shape()
  4687. # create the selection box around the selected object
  4688. if self.defaults['global_selection_shape'] is True:
  4689. self.draw_selection_shape(curr_sel_obj)
  4690. # self.inform.emit('[selected] %s: %s selected' %
  4691. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4692. if curr_sel_obj.kind == 'gerber':
  4693. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4694. color='green', name=str(curr_sel_obj.options['name'])))
  4695. elif curr_sel_obj.kind == 'excellon':
  4696. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4697. color='brown', name=str(curr_sel_obj.options['name'])))
  4698. elif curr_sel_obj.kind == 'cncjob':
  4699. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4700. color='blue', name=str(curr_sel_obj.options['name'])))
  4701. elif curr_sel_obj.kind == 'geometry':
  4702. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4703. color='red', name=str(curr_sel_obj.options['name'])))
  4704. # for obj in self.collection.get_list():
  4705. # obj.plot()
  4706. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  4707. # TODO: on selected objects change the object colors and do not draw the selection box
  4708. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  4709. except Exception as e:
  4710. log.error("[ERROR] Something went bad. %s" % str(e))
  4711. return
  4712. def delete_hover_shape(self):
  4713. self.hover_shapes.clear()
  4714. self.hover_shapes.redraw()
  4715. def draw_hover_shape(self, sel_obj, color=None):
  4716. """
  4717. :param sel_obj: the object for which the hover shape must be drawn
  4718. :return:
  4719. """
  4720. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  4721. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  4722. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  4723. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  4724. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  4725. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4726. hover_rect = hover_rect.buffer(-0.1)
  4727. hover_rect = hover_rect.buffer(0.2)
  4728. else:
  4729. hover_rect = hover_rect.buffer(-0.00393)
  4730. hover_rect = hover_rect.buffer(0.00787)
  4731. if color:
  4732. face = Color(color)
  4733. face.alpha = 0.2
  4734. outline = Color(color, alpha=0.8)
  4735. else:
  4736. face = Color(self.defaults['global_sel_fill'])
  4737. face.alpha = 0.2
  4738. outline = self.defaults['global_sel_line']
  4739. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  4740. def delete_selection_shape(self):
  4741. self.move_tool.sel_shapes.clear()
  4742. self.move_tool.sel_shapes.redraw()
  4743. def draw_selection_shape(self, sel_obj, color=None):
  4744. """
  4745. :param sel_obj: the object for which the selection shape must be drawn
  4746. :return:
  4747. """
  4748. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  4749. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  4750. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  4751. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  4752. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  4753. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4754. sel_rect = sel_rect.buffer(-0.1)
  4755. sel_rect = sel_rect.buffer(0.2)
  4756. else:
  4757. sel_rect = sel_rect.buffer(-0.00393)
  4758. sel_rect = sel_rect.buffer(0.00787)
  4759. if color:
  4760. face = Color(color, alpha=0.2)
  4761. outline = Color(color, alpha=0.8)
  4762. else:
  4763. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  4764. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  4765. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=outline,
  4766. face_color=face, update=True, layer=0, tolerance=None))
  4767. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  4768. """
  4769. :param old_coords: old coordinates
  4770. :param coords: new coordinates
  4771. :return:
  4772. """
  4773. if 'color' in kwargs:
  4774. color = kwargs['color']
  4775. else:
  4776. color = self.defaults['global_sel_line']
  4777. if 'face_color' in kwargs:
  4778. face_color = kwargs['face_color']
  4779. else:
  4780. face_color = self.defaults['global_sel_fill']
  4781. x0, y0 = old_coords
  4782. x1, y1 = coords
  4783. pt1 = (x0, y0)
  4784. pt2 = (x1, y0)
  4785. pt3 = (x1, y1)
  4786. pt4 = (x0, y1)
  4787. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  4788. color_t = Color(face_color)
  4789. color_t.alpha = 0.3
  4790. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  4791. layer=0, tolerance=None)
  4792. def on_file_new_click(self):
  4793. if self.collection.get_list() and self.should_we_save:
  4794. msgbox = QtWidgets.QMessageBox()
  4795. # msgbox.setText("<B>Save changes ...</B>")
  4796. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  4797. "Creating a New project will delete them.\n"
  4798. "Do you want to Save the project?"))
  4799. msgbox.setWindowTitle(_("Save changes"))
  4800. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4801. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4802. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4803. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4804. msgbox.setDefaultButton(bt_yes)
  4805. msgbox.exec_()
  4806. response = msgbox.clickedButton()
  4807. if response == bt_yes:
  4808. self.on_file_saveprojectas()
  4809. elif response == bt_cancel:
  4810. return
  4811. elif response == bt_no:
  4812. self.on_file_new()
  4813. else:
  4814. self.on_file_new()
  4815. self.inform.emit(_("[success] New Project created..."))
  4816. def on_file_new(self):
  4817. """
  4818. Callback for menu item File->New. Returns the application to its
  4819. startup state. This method is thread-safe.
  4820. :return: None
  4821. """
  4822. self.report_usage("on_file_new")
  4823. # Remove everything from memory
  4824. App.log.debug("on_file_new()")
  4825. if self.call_source != 'app':
  4826. self.editor2object(cleanup=True)
  4827. ### EDITOR section
  4828. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  4829. self.exc_editor = FlatCAMExcEditor(self)
  4830. self.grb_editor = FlatCAMGrbEditor(self)
  4831. # Clear pool
  4832. self.clear_pool()
  4833. #delete shapes left drawn from mark shape_collections, if any
  4834. for obj in self.collection.get_list():
  4835. try:
  4836. obj.mark_shapes.enabled = False
  4837. obj.mark_shapes.clear(update=True)
  4838. except:
  4839. pass
  4840. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  4841. self.init_tcl()
  4842. self.delete_selection_shape()
  4843. self.collection.delete_all()
  4844. self.setup_component_editor()
  4845. # Clear project filename
  4846. self.project_filename = None
  4847. # Load the application defaults
  4848. self.load_defaults(filename='current_defaults')
  4849. # Re-fresh project options
  4850. self.on_options_app2project()
  4851. # Init Tools
  4852. self.init_tools()
  4853. # Close any Tabs opened in the Plot Tab Area section
  4854. for index in range(self.ui.plot_tab_area.count()):
  4855. self.ui.plot_tab_area.closeTab(index)
  4856. # for whatever reason previous command does not close the last tab so I do it manually
  4857. self.ui.plot_tab_area.closeTab(0)
  4858. # # And then add again the Plot Area
  4859. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4860. self.ui.plot_tab_area.protectTab(0)
  4861. # take the focus of the Notebook on Project Tab.
  4862. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4863. def obj_properties(self):
  4864. self.report_usage("obj_properties()")
  4865. self.properties_tool.run(toggle=False)
  4866. def on_project_context_save(self):
  4867. obj = self.collection.get_active()
  4868. if type(obj) == FlatCAMGeometry:
  4869. self.on_file_exportdxf()
  4870. elif type(obj) == FlatCAMExcellon:
  4871. self.on_file_saveexcellon()
  4872. elif type(obj) == FlatCAMCNCjob:
  4873. obj.on_exportgcode_button_click()
  4874. elif type(obj) == FlatCAMGerber:
  4875. self.on_file_savegerber()
  4876. def obj_move(self):
  4877. self.report_usage("obj_move()")
  4878. self.move_tool.run(toggle=False)
  4879. def on_fileopengerber(self):
  4880. """
  4881. File menu callback for opening a Gerber.
  4882. :return: None
  4883. """
  4884. self.report_usage("on_fileopengerber")
  4885. App.log.debug("on_fileopengerber()")
  4886. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  4887. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  4888. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  4889. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  4890. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  4891. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  4892. "Allegro Files (*.art);;" \
  4893. "Mentor Files (*.pho *.gdo);;" \
  4894. "All Files (*.*)"
  4895. try:
  4896. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  4897. directory=self.get_last_folder(), filter=_filter_)
  4898. except TypeError:
  4899. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  4900. filenames = [str(filename) for filename in filenames]
  4901. if len(filenames) == 0:
  4902. self.inform.emit(_("[WARNING_NOTCL] Open Gerber cancelled."))
  4903. else:
  4904. for filename in filenames:
  4905. if filename != '':
  4906. self.worker_task.emit({'fcn': self.open_gerber,
  4907. 'params': [filename]})
  4908. def on_fileopenexcellon(self):
  4909. """
  4910. File menu callback for opening an Excellon file.
  4911. :return: None
  4912. """
  4913. self.report_usage("on_fileopenexcellon")
  4914. App.log.debug("on_fileopenexcellon()")
  4915. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc);;" \
  4916. "All Files (*.*)"
  4917. try:
  4918. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  4919. directory=self.get_last_folder(), filter=_filter_)
  4920. except TypeError:
  4921. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  4922. filenames = [str(filename) for filename in filenames]
  4923. if len(filenames) == 0:
  4924. self.inform.emit(_("[WARNING_NOTCL] Open Excellon cancelled."))
  4925. else:
  4926. for filename in filenames:
  4927. if filename != '':
  4928. self.worker_task.emit({'fcn': self.open_excellon,
  4929. 'params': [filename]})
  4930. def on_fileopengcode(self):
  4931. """
  4932. File menu call back for opening gcode.
  4933. :return: None
  4934. """
  4935. self.report_usage("on_fileopengcode")
  4936. App.log.debug("on_fileopengcode()")
  4937. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  4938. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  4939. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  4940. "All Files (*.*)"
  4941. try:
  4942. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  4943. directory=self.get_last_folder(), filter=_filter_)
  4944. except TypeError:
  4945. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  4946. filenames = [str(filename) for filename in filenames]
  4947. if len(filenames) == 0:
  4948. self.inform.emit(_("[WARNING_NOTCL] Open G-Code cancelled."))
  4949. else:
  4950. for filename in filenames:
  4951. if filename != '':
  4952. self.worker_task.emit({'fcn': self.open_gcode,
  4953. 'params': [filename]})
  4954. def on_file_openproject(self):
  4955. """
  4956. File menu callback for opening a project.
  4957. :return: None
  4958. """
  4959. self.report_usage("on_file_openproject")
  4960. App.log.debug("on_file_openproject()")
  4961. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  4962. try:
  4963. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  4964. directory=self.get_last_folder(), filter=_filter_)
  4965. except TypeError:
  4966. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter = _filter_)
  4967. # The Qt methods above will return a QString which can cause problems later.
  4968. # So far json.dump() will fail to serialize it.
  4969. # TODO: Improve the serialization methods and remove this fix.
  4970. filename = str(filename)
  4971. if filename == "":
  4972. self.inform.emit(_("[WARNING_NOTCL] Open Project cancelled."))
  4973. else:
  4974. # self.worker_task.emit({'fcn': self.open_project,
  4975. # 'params': [filename]})
  4976. # The above was failing because open_project() is not
  4977. # thread safe. The new_project()
  4978. self.open_project(filename)
  4979. def on_file_openconfig(self):
  4980. """
  4981. File menu callback for opening a config file.
  4982. :return: None
  4983. """
  4984. self.report_usage("on_file_openconfig")
  4985. App.log.debug("on_file_openconfig()")
  4986. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  4987. try:
  4988. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  4989. directory=self.data_path, filter=_filter_)
  4990. except TypeError:
  4991. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  4992. filter = _filter_)
  4993. if filename == "":
  4994. self.inform.emit(_("[WARNING_NOTCL Open Config cancelled."))
  4995. else:
  4996. self.open_config_file(filename)
  4997. def on_file_exportsvg(self):
  4998. """
  4999. Callback for menu item File->Export SVG.
  5000. :return: None
  5001. """
  5002. self.report_usage("on_file_exportsvg")
  5003. App.log.debug("on_file_exportsvg()")
  5004. obj = self.collection.get_active()
  5005. if obj is None:
  5006. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  5007. msg = _("Please Select a Geometry object to export")
  5008. msgbox = QtWidgets.QMessageBox()
  5009. msgbox.setInformativeText(msg)
  5010. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5011. msgbox.setDefaultButton(bt_ok)
  5012. msgbox.exec_()
  5013. return
  5014. # Check for more compatible types and add as required
  5015. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  5016. and not isinstance(obj, FlatCAMExcellon)):
  5017. msg = _("[ERROR_NOTCL] Only Geometry, Gerber and CNCJob objects can be used.")
  5018. msgbox = QtWidgets.QMessageBox()
  5019. msgbox.setInformativeText(msg)
  5020. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5021. msgbox.setDefaultButton(bt_ok)
  5022. msgbox.exec_()
  5023. return
  5024. name = self.collection.get_active().options["name"]
  5025. filter = "SVG File (*.svg);;All Files (*.*)"
  5026. try:
  5027. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5028. caption=_("Export SVG"),
  5029. directory=self.get_last_save_folder() + '/' + str(name),
  5030. filter=filter)
  5031. except TypeError:
  5032. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=filter)
  5033. filename = str(filename)
  5034. if filename == "":
  5035. self.inform.emit(_("[WARNING_NOTCL] Export SVG cancelled."))
  5036. return
  5037. else:
  5038. self.export_svg(name, filename)
  5039. if self.defaults["global_open_style"] is False:
  5040. self.file_opened.emit("SVG", filename)
  5041. self.file_saved.emit("SVG", filename)
  5042. def on_file_exportpng(self):
  5043. self.report_usage("on_file_exportpng")
  5044. App.log.debug("on_file_exportpng()")
  5045. image = _screenshot()
  5046. data = np.asarray(image)
  5047. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5048. self.inform.emit(_('[[WARNING_NOTCL]] Data must be a 3D array with last dimension 3 or 4'))
  5049. return
  5050. filter_ = "PNG File (*.png);;All Files (*.*)"
  5051. try:
  5052. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5053. caption=_("Export PNG Image"),
  5054. directory=self.get_last_save_folder() + '/png_' + self.date,
  5055. filter=filter_)
  5056. except TypeError:
  5057. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  5058. filename = str(filename)
  5059. if filename == "":
  5060. self.inform.emit(_("Export PNG cancelled."))
  5061. return
  5062. else:
  5063. write_png(filename, data)
  5064. if self.defaults["global_open_style"] is False:
  5065. self.file_opened.emit("png", filename)
  5066. self.file_saved.emit("png", filename)
  5067. def on_file_savegerber(self):
  5068. """
  5069. Callback for menu item File->Export Gerber.
  5070. :return: None
  5071. """
  5072. self.report_usage("on_file_savegerber")
  5073. App.log.debug("on_file_savegerber()")
  5074. obj = self.collection.get_active()
  5075. if obj is None:
  5076. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Gerber object to export."))
  5077. return
  5078. # Check for more compatible types and add as required
  5079. if not isinstance(obj, FlatCAMGerber):
  5080. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files..."))
  5081. return
  5082. name = self.collection.get_active().options["name"]
  5083. filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5084. try:
  5085. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5086. caption="Save Gerber source file",
  5087. directory=self.get_last_save_folder() + '/' + name,
  5088. filter=filter)
  5089. except TypeError:
  5090. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=filter)
  5091. filename = str(filename)
  5092. if filename == "":
  5093. self.inform.emit(_("[WARNING_NOTCL] Save Gerber source file cancelled."))
  5094. return
  5095. else:
  5096. self.save_source_file(name, filename)
  5097. if self.defaults["global_open_style"] is False:
  5098. self.file_opened.emit("Gerber", filename)
  5099. self.file_saved.emit("Gerber", filename)
  5100. def on_file_saveexcellon(self):
  5101. """
  5102. Callback for menu item File->Export Gerber.
  5103. :return: None
  5104. """
  5105. self.report_usage("on_file_saveexcellon")
  5106. App.log.debug("on_file_saveexcellon()")
  5107. obj = self.collection.get_active()
  5108. if obj is None:
  5109. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Excellon object to export."))
  5110. return
  5111. # Check for more compatible types and add as required
  5112. if not isinstance(obj, FlatCAMExcellon):
  5113. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  5114. return
  5115. name = self.collection.get_active().options["name"]
  5116. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5117. try:
  5118. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5119. caption=_("Save Excellon source file"),
  5120. directory=self.get_last_save_folder() + '/' + name,
  5121. filter=filter)
  5122. except TypeError:
  5123. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=filter)
  5124. filename = str(filename)
  5125. if filename == "":
  5126. self.inform.emit(_("[WARNING_NOTCL] Saving Excellon source file cancelled."))
  5127. return
  5128. else:
  5129. self.save_source_file(name, filename)
  5130. if self.defaults["global_open_style"] is False:
  5131. self.file_opened.emit("Excellon", filename)
  5132. self.file_saved.emit("Excellon", filename)
  5133. def on_file_exportexcellon(self):
  5134. """
  5135. Callback for menu item File->Export->Excellon.
  5136. :return: None
  5137. """
  5138. self.report_usage("on_file_exportexcellon")
  5139. App.log.debug("on_file_exportexcellon()")
  5140. obj = self.collection.get_active()
  5141. if obj is None:
  5142. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please Select an Excellon object to export."))
  5143. return
  5144. # Check for more compatible types and add as required
  5145. if not isinstance(obj, FlatCAMExcellon):
  5146. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  5147. return
  5148. name = self.collection.get_active().options["name"]
  5149. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5150. try:
  5151. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5152. caption=_("Export Excellon"),
  5153. directory=self.get_last_save_folder() + '/' + name,
  5154. filter=filter)
  5155. except TypeError:
  5156. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=filter)
  5157. filename = str(filename)
  5158. if filename == "":
  5159. self.inform.emit(_("[WARNING_NOTCL] Export Excellon cancelled."))
  5160. return
  5161. else:
  5162. self.export_excellon(name, filename)
  5163. if self.defaults["global_open_style"] is False:
  5164. self.file_opened.emit("Excellon", filename)
  5165. self.file_saved.emit("Excellon", filename)
  5166. def on_file_exportgerber(self):
  5167. """
  5168. Callback for menu item File->Export->Gerber.
  5169. :return: None
  5170. """
  5171. self.report_usage("on_file_exportgerber")
  5172. App.log.debug("on_file_exportgerber()")
  5173. obj = self.collection.get_active()
  5174. if obj is None:
  5175. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please Select an Gerber object to export."))
  5176. return
  5177. # Check for more compatible types and add as required
  5178. if not isinstance(obj, FlatCAMGerber):
  5179. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files..."))
  5180. return
  5181. name = self.collection.get_active().options["name"]
  5182. filter = "Gerber File (*.GBR);;All Files (*.*)"
  5183. try:
  5184. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5185. caption=_("Export Gerber"),
  5186. directory=self.get_last_save_folder() + '/' + name,
  5187. filter=filter)
  5188. except TypeError:
  5189. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=filter)
  5190. filename = str(filename)
  5191. if filename == "":
  5192. self.inform.emit(_("[WARNING_NOTCL] Export Gerber cancelled."))
  5193. return
  5194. else:
  5195. self.export_gerber(name, filename)
  5196. if self.defaults["global_open_style"] is False:
  5197. self.file_opened.emit("Gerber", filename)
  5198. self.file_saved.emit("Gerber", filename)
  5199. def on_file_exportdxf(self):
  5200. """
  5201. Callback for menu item File->Export DXF.
  5202. :return: None
  5203. """
  5204. self.report_usage("on_file_exportdxf")
  5205. App.log.debug("on_file_exportdxf()")
  5206. obj = self.collection.get_active()
  5207. if obj is None:
  5208. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  5209. msg = _("Please Select a Geometry object to export")
  5210. msgbox = QtWidgets.QMessageBox()
  5211. msgbox.setInformativeText(msg)
  5212. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5213. msgbox.setDefaultButton(bt_ok)
  5214. msgbox.exec_()
  5215. return
  5216. # Check for more compatible types and add as required
  5217. if not isinstance(obj, FlatCAMGeometry):
  5218. msg = _("[ERROR_NOTCL] Only Geometry objects can be used.")
  5219. msgbox = QtWidgets.QMessageBox()
  5220. msgbox.setInformativeText(msg)
  5221. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5222. msgbox.setDefaultButton(bt_ok)
  5223. msgbox.exec_()
  5224. return
  5225. name = self.collection.get_active().options["name"]
  5226. filter = "DXF File (*.DXF);;All Files (*.*)"
  5227. try:
  5228. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5229. caption=_("Export DXF"),
  5230. directory=self.get_last_save_folder() + '/' + name,
  5231. filter=filter)
  5232. except TypeError:
  5233. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"), filter=filter)
  5234. filename = str(filename)
  5235. if filename == "":
  5236. self.inform.emit(_("[WARNING_NOTCL] Export DXF cancelled."))
  5237. return
  5238. else:
  5239. self.export_dxf(name, filename)
  5240. if self.defaults["global_open_style"] is False:
  5241. self.file_opened.emit("DXF", filename)
  5242. self.file_saved.emit("DXF", filename)
  5243. def on_file_importsvg(self, type_of_obj):
  5244. """
  5245. Callback for menu item File->Import SVG.
  5246. :param type_of_obj: to import the SVG as Geometry or as Gerber
  5247. :type type_of_obj: str
  5248. :return: None
  5249. """
  5250. self.report_usage("on_file_importsvg")
  5251. App.log.debug("on_file_importsvg()")
  5252. filter = "SVG File (*.svg);;All Files (*.*)"
  5253. try:
  5254. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5255. directory=self.get_last_folder(), filter=filter)
  5256. except TypeError:
  5257. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"), filter=filter)
  5258. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  5259. type_of_obj = "geometry"
  5260. filenames = [str(filename) for filename in filenames]
  5261. if len(filenames) == 0:
  5262. self.inform.emit(_("[WARNING_NOTCL] Open SVG cancelled."))
  5263. else:
  5264. for filename in filenames:
  5265. if filename != '':
  5266. self.worker_task.emit({'fcn': self.import_svg,
  5267. 'params': [filename, type_of_obj]})
  5268. def on_file_importdxf(self, type_of_obj):
  5269. """
  5270. Callback for menu item File->Import DXF.
  5271. :param type_of_obj: to import the DXF as Geometry or as Gerber
  5272. :type type_of_obj: str
  5273. :return: None
  5274. """
  5275. self.report_usage("on_file_importdxf")
  5276. App.log.debug("on_file_importdxf()")
  5277. filter = "DXF File (*.DXF);;All Files (*.*)"
  5278. try:
  5279. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5280. directory=self.get_last_folder(), filter=filter)
  5281. except TypeError:
  5282. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"), filter=filter)
  5283. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  5284. type_of_obj = "geometry"
  5285. filenames = [str(filename) for filename in filenames]
  5286. if len(filenames) == 0:
  5287. self.inform.emit(_("[WARNING_NOTCL] Open DXF cancelled."))
  5288. else:
  5289. for filename in filenames:
  5290. if filename != '':
  5291. self.worker_task.emit({'fcn': self.import_dxf,
  5292. 'params': [filename, type_of_obj]})
  5293. ###################################################################################################################
  5294. ### The following section has the functions that are displayed are call the Editoe tab CNCJob Tab #################
  5295. ###################################################################################################################
  5296. def init_code_editor(self, name):
  5297. # Signals section
  5298. # Disconnect the old signals
  5299. self.ui.buttonOpen.clicked.disconnect()
  5300. self.ui.buttonSave.clicked.disconnect()
  5301. # add the tab if it was closed
  5302. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _('%s') % name)
  5303. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  5304. # delete the absolute and relative position and messages in the infobar
  5305. self.ui.position_label.setText("")
  5306. self.ui.rel_position_label.setText("")
  5307. # first clear previous text in text editor (if any)
  5308. self.ui.code_editor.clear()
  5309. self.ui.code_editor.setReadOnly(False)
  5310. self.toggle_codeeditor = True
  5311. self.ui.code_editor.completer_enable = False
  5312. # Switch plot_area to CNCJob tab
  5313. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  5314. def on_view_source(self):
  5315. try:
  5316. obj = self.collection.get_active()
  5317. except:
  5318. self.inform.emit(_("[WARNING_NOTCL] Select an Gerber or Excellon file to view it's source file."))
  5319. return 'fail'
  5320. # then append the text from GCode to the text editor
  5321. try:
  5322. file = StringIO(obj.source_file)
  5323. except AttributeError:
  5324. self.inform.emit(_("[WARNING_NOTCL] There is no selected object for which to see it's source file code."))
  5325. return 'fail'
  5326. if obj.kind == 'gerber':
  5327. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  5328. elif obj.kind == 'excellon':
  5329. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  5330. self.init_code_editor(name=_("Source Editor"))
  5331. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  5332. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  5333. try:
  5334. for line in file:
  5335. proc_line = str(line).strip('\n')
  5336. self.ui.code_editor.append(proc_line)
  5337. except Exception as e:
  5338. log.debug('App.on_view_source() -->%s' % str(e))
  5339. self.inform.emit(_('[ERROR]App.on_view_source() -->%s') % str(e))
  5340. return
  5341. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5342. self.handleTextChanged()
  5343. self.ui.show()
  5344. def on_toggle_code_editor(self):
  5345. self.report_usage("on_toggle_code_editor()")
  5346. if self.toggle_codeeditor is False:
  5347. self.init_code_editor(name=_("Code Editor"))
  5348. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  5349. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  5350. else:
  5351. for idx in range(self.ui.plot_tab_area.count()):
  5352. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  5353. self.ui.plot_tab_area.closeTab(idx)
  5354. break
  5355. self.toggle_codeeditor = False
  5356. def on_filenewscript(self):
  5357. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5358. self.init_code_editor(name=_("Script Editor"))
  5359. self.ui.code_editor.completer_enable = True
  5360. self.ui.code_editor.append(_(
  5361. "#\n"
  5362. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  5363. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  5364. "#\n\n"
  5365. "# FlatCAM commands list:\n"
  5366. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, Cncjob,\n"
  5367. "# Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames, GetSys,\n"
  5368. "# ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillHoles, Mirror, New,\n"
  5369. "# NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject, Options, Paint, Panelize,\n"
  5370. "# Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,SubtractRectangle, Version,\n"
  5371. "# WriteGCode\n"
  5372. "#\n\n"
  5373. ))
  5374. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  5375. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  5376. self.handleTextChanged()
  5377. self.ui.code_editor.show()
  5378. def on_fileopenscript(self):
  5379. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  5380. try:
  5381. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  5382. directory=self.get_last_folder(), filter=_filter_)
  5383. except TypeError:
  5384. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  5385. # The Qt methods above will return a QString which can cause problems later.
  5386. # So far json.dump() will fail to serialize it.
  5387. # TODO: Improve the serialization methods and remove this fix.
  5388. filename = str(filename)
  5389. if filename == "":
  5390. self.inform.emit(_("[WARNING_NOTCL] Open TCL script cancelled."))
  5391. else:
  5392. self.on_filenewscript()
  5393. try:
  5394. with open(filename, "r") as opened_script:
  5395. try:
  5396. for line in opened_script:
  5397. proc_line = str(line).strip('\n')
  5398. self.ui.code_editor.append(proc_line)
  5399. except Exception as e:
  5400. log.debug('App.on_fileopenscript() -->%s' % str(e))
  5401. self.inform.emit(_('[ERROR]App.on_fileopenscript() -->%s') % str(e))
  5402. return
  5403. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5404. self.handleTextChanged()
  5405. self.ui.show()
  5406. except Exception as e:
  5407. log.debug("App.on_fileopenscript() -> %s" % str(e))
  5408. def on_filerunscript(self, name=None):
  5409. """
  5410. File menu callback for loading and running a TCL script.
  5411. :return: None
  5412. """
  5413. self.report_usage("on_filerunscript")
  5414. App.log.debug("on_file_runscript()")
  5415. if name:
  5416. filename = name
  5417. else:
  5418. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  5419. try:
  5420. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  5421. directory=self.get_last_folder(), filter=_filter_)
  5422. except TypeError:
  5423. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  5424. # The Qt methods above will return a QString which can cause problems later.
  5425. # So far json.dump() will fail to serialize it.
  5426. # TODO: Improve the serialization methods and remove this fix.
  5427. filename = str(filename)
  5428. if filename == "":
  5429. self.inform.emit(_("[WARNING_NOTCL] Run TCL script cancelled."))
  5430. else:
  5431. try:
  5432. with open(filename, "r") as tcl_script:
  5433. cmd_line_shellfile_content = tcl_script.read()
  5434. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  5435. except Exception as e:
  5436. log.debug("App.on_filerunscript() -> %s" % str(e))
  5437. sys.exit(2)
  5438. def on_file_saveproject(self):
  5439. """
  5440. Callback for menu item File->Save Project. Saves the project to
  5441. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  5442. if set to None. The project is saved by calling ``self.save_project()``.
  5443. :return: None
  5444. """
  5445. self.report_usage("on_file_saveproject")
  5446. if self.project_filename is None:
  5447. self.on_file_saveprojectas()
  5448. else:
  5449. self.worker_task.emit({'fcn': self.save_project,
  5450. 'params': [self.project_filename]})
  5451. if self.defaults["global_open_style"] is False:
  5452. self.file_opened.emit("project", self.project_filename)
  5453. self.file_saved.emit("project", self.project_filename)
  5454. self.should_we_save = False
  5455. def on_file_saveprojectas(self, make_copy=False, thread=True, quit=False):
  5456. """
  5457. Callback for menu item File->Save Project As... Opens a file
  5458. chooser and saves the project to the given file via
  5459. ``self.save_project()``.
  5460. :return: None
  5461. """
  5462. self.report_usage("on_file_saveprojectas")
  5463. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  5464. try:
  5465. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5466. caption=_("Save Project As ..."),
  5467. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  5468. filter=filter_)
  5469. except TypeError:
  5470. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  5471. filename = str(filename)
  5472. if filename == '':
  5473. self.inform.emit(_("[WARNING_NOTCL] Save Project cancelled."))
  5474. return
  5475. try:
  5476. f = open(filename, 'r')
  5477. f.close()
  5478. exists = True
  5479. except IOError:
  5480. exists = False
  5481. if thread is True:
  5482. self.worker_task.emit({'fcn': self.save_project,
  5483. 'params': [filename, quit]})
  5484. else:
  5485. self.save_project(filename, quit)
  5486. # self.save_project(filename)
  5487. if self.defaults["global_open_style"] is False:
  5488. self.file_opened.emit("project", filename)
  5489. self.file_saved.emit("project", filename)
  5490. if not make_copy:
  5491. self.project_filename = filename
  5492. self.should_we_save = False
  5493. def export_svg(self, obj_name, filename, scale_factor=0.00):
  5494. """
  5495. Exports a Geometry Object to an SVG file.
  5496. :param filename: Path to the SVG file to save to.
  5497. :return:
  5498. """
  5499. self.report_usage("export_svg()")
  5500. if filename is None:
  5501. filename = self.defaults["global_last_save_folder"]
  5502. self.log.debug("export_svg()")
  5503. try:
  5504. obj = self.collection.get_by_name(str(obj_name))
  5505. except:
  5506. # TODO: The return behavior has not been established... should raise exception?
  5507. return "Could not retrieve object: %s" % obj_name
  5508. with self.proc_container.new(_("Exporting SVG")) as proc:
  5509. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5510. # Determine bounding area for svg export
  5511. bounds = obj.bounds()
  5512. size = obj.size()
  5513. # Convert everything to strings for use in the xml doc
  5514. svgwidth = str(size[0])
  5515. svgheight = str(size[1])
  5516. minx = str(bounds[0])
  5517. miny = str(bounds[1] - size[1])
  5518. uom = obj.units.lower()
  5519. # Add a SVG Header and footer to the svg output from shapely
  5520. # The transform flips the Y Axis so that everything renders
  5521. # properly within svg apps such as inkscape
  5522. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5523. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5524. svg_header += 'width="' + svgwidth + uom + '" '
  5525. svg_header += 'height="' + svgheight + uom + '" '
  5526. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  5527. svg_header += '<g transform="scale(1,-1)">'
  5528. svg_footer = '</g> </svg>'
  5529. svg_elem = svg_header + exported_svg + svg_footer
  5530. # Parse the xml through a xml parser just to add line feeds
  5531. # and to make it look more pretty for the output
  5532. svgcode = parse_xml_string(svg_elem)
  5533. with open(filename, 'w') as fp:
  5534. fp.write(svgcode.toprettyxml())
  5535. if self.defaults["global_open_style"] is False:
  5536. self.file_opened.emit("SVG", filename)
  5537. self.file_saved.emit("SVG", filename)
  5538. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5539. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  5540. """
  5541. Exports a Geometry Object to an SVG file in negative.
  5542. :param filename: Path to the SVG file to save to.
  5543. :param: use_thread: If True use threads
  5544. :type: Bool
  5545. :return:
  5546. """
  5547. self.report_usage("export_negative()")
  5548. if filename is None:
  5549. filename = self.defaults["global_last_save_folder"]
  5550. self.log.debug("export_svg() negative")
  5551. try:
  5552. obj = self.collection.get_by_name(str(obj_name))
  5553. except:
  5554. # TODO: The return behavior has not been established... should raise exception?
  5555. return "Could not retrieve object: %s" % obj_name
  5556. try:
  5557. box = self.collection.get_by_name(str(box_name))
  5558. except:
  5559. # TODO: The return behavior has not been established... should raise exception?
  5560. return "Could not retrieve object: %s" % box_name
  5561. if box is None:
  5562. self.inform.emit(_("[WARNING_NOTCL] No object Box. Using instead %s") % obj)
  5563. box = obj
  5564. def make_negative_film():
  5565. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5566. self.progress.emit(40)
  5567. # Determine bounding area for svg export
  5568. bounds = box.bounds()
  5569. size = box.size()
  5570. uom = obj.units.lower()
  5571. # Convert everything to strings for use in the xml doc
  5572. svgwidth = str(size[0] + (2 * boundary))
  5573. svgheight = str(size[1] + (2 * boundary))
  5574. minx = str(bounds[0] - boundary)
  5575. miny = str(bounds[1] + boundary + size[1])
  5576. miny_rect = str(bounds[1] - boundary)
  5577. # Add a SVG Header and footer to the svg output from shapely
  5578. # The transform flips the Y Axis so that everything renders
  5579. # properly within svg apps such as inkscape
  5580. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5581. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5582. svg_header += 'width="' + svgwidth + uom + '" '
  5583. svg_header += 'height="' + svgheight + uom + '" '
  5584. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  5585. svg_header += '>'
  5586. svg_header += '<g transform="scale(1,-1)">'
  5587. svg_footer = '</g> </svg>'
  5588. self.progress.emit(60)
  5589. # Change the attributes of the exported SVG
  5590. # We don't need stroke-width - wrong, we do when we have lines with certain width
  5591. # We set opacity to maximum
  5592. # We set the color to WHITE
  5593. root = ET.fromstring(exported_svg)
  5594. for child in root:
  5595. child.set('fill', '#FFFFFF')
  5596. child.set('opacity', '1.0')
  5597. child.set('stroke', '#FFFFFF')
  5598. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  5599. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  5600. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  5601. first_svg_elem_tag = 'rect'
  5602. first_svg_elem_attribs = {
  5603. 'x': minx,
  5604. 'y': miny_rect,
  5605. 'width': svgwidth,
  5606. 'height': svgheight,
  5607. 'id': 'neg_rect',
  5608. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  5609. }
  5610. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  5611. exported_svg = ET.tostring(root)
  5612. svg_elem = svg_header + str(exported_svg) + svg_footer
  5613. self.progress.emit(80)
  5614. # Parse the xml through a xml parser just to add line feeds
  5615. # and to make it look more pretty for the output
  5616. doc = parse_xml_string(svg_elem)
  5617. with open(filename, 'w') as fp:
  5618. fp.write(doc.toprettyxml())
  5619. self.progress.emit(100)
  5620. if self.defaults["global_open_style"] is False:
  5621. self.file_opened.emit("SVG", filename)
  5622. self.file_saved.emit("SVG", filename)
  5623. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5624. if use_thread is True:
  5625. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  5626. def job_thread_film(app_obj):
  5627. try:
  5628. make_negative_film()
  5629. except Exception as e:
  5630. proc.done()
  5631. return
  5632. proc.done()
  5633. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  5634. else:
  5635. make_negative_film()
  5636. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  5637. """
  5638. Exports a Geometry Object to an SVG file in negative.
  5639. :param filename: Path to the SVG file to save to.
  5640. :param: use_thread: If True use threads
  5641. :type: Bool
  5642. :return:
  5643. """
  5644. self.report_usage("export_svg_black()")
  5645. if filename is None:
  5646. filename = self.defaults["global_last_save_folder"]
  5647. self.log.debug("export_svg() black")
  5648. try:
  5649. obj = self.collection.get_by_name(str(obj_name))
  5650. except:
  5651. # TODO: The return behavior has not been established... should raise exception?
  5652. return "Could not retrieve object: %s" % obj_name
  5653. try:
  5654. box = self.collection.get_by_name(str(box_name))
  5655. except:
  5656. # TODO: The return behavior has not been established... should raise exception?
  5657. return "Could not retrieve object: %s" % box_name
  5658. if box is None:
  5659. self.inform.emit(_("[WARNING_NOTCL] No object Box. Using instead %s") % obj)
  5660. box = obj
  5661. def make_black_film():
  5662. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5663. self.progress.emit(40)
  5664. # Change the attributes of the exported SVG
  5665. # We don't need stroke-width
  5666. # We set opacity to maximum
  5667. # We set the colour to WHITE
  5668. root = ET.fromstring(exported_svg)
  5669. for child in root:
  5670. child.set('fill', '#000000')
  5671. child.set('opacity', '1.0')
  5672. child.set('stroke', '#000000')
  5673. exported_svg = ET.tostring(root)
  5674. # Determine bounding area for svg export
  5675. bounds = box.bounds()
  5676. size = box.size()
  5677. # This contain the measure units
  5678. uom = obj.units.lower()
  5679. # Define a boundary around SVG of about 1.0mm (~39mils)
  5680. if uom in "mm":
  5681. boundary = 1.0
  5682. else:
  5683. boundary = 0.0393701
  5684. self.progress.emit(80)
  5685. # Convert everything to strings for use in the xml doc
  5686. svgwidth = str(size[0] + (2 * boundary))
  5687. svgheight = str(size[1] + (2 * boundary))
  5688. minx = str(bounds[0] - boundary)
  5689. miny = str(bounds[1] + boundary + size[1])
  5690. self.log.debug(minx)
  5691. self.log.debug(miny)
  5692. # Add a SVG Header and footer to the svg output from shapely
  5693. # The transform flips the Y Axis so that everything renders
  5694. # properly within svg apps such as inkscape
  5695. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5696. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5697. svg_header += 'width="' + svgwidth + uom + '" '
  5698. svg_header += 'height="' + svgheight + uom + '" '
  5699. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  5700. svg_header += '>'
  5701. svg_header += '<g transform="scale(1,-1)">'
  5702. svg_footer = '</g> </svg>'
  5703. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  5704. self.progress.emit(90)
  5705. # Parse the xml through a xml parser just to add line feeds
  5706. # and to make it look more pretty for the output
  5707. doc = parse_xml_string(svg_elem)
  5708. with open(filename, 'w') as fp:
  5709. fp.write(doc.toprettyxml())
  5710. self.progress.emit(100)
  5711. if self.defaults["global_open_style"] is False:
  5712. self.file_opened.emit("SVG", filename)
  5713. self.file_saved.emit("SVG", filename)
  5714. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5715. if use_thread is True:
  5716. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  5717. def job_thread_film(app_obj):
  5718. try:
  5719. make_black_film()
  5720. except Exception as e:
  5721. proc.done()
  5722. return
  5723. proc.done()
  5724. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  5725. else:
  5726. make_black_film()
  5727. def save_source_file(self, obj_name, filename, use_thread=True):
  5728. """
  5729. Exports a Gerber Object to an Gerber file.
  5730. :param filename: Path to the Gerber file to save to.
  5731. :return:
  5732. """
  5733. self.report_usage("save source file()")
  5734. if filename is None:
  5735. filename = self.defaults["global_last_save_folder"]
  5736. self.log.debug("save source file()")
  5737. obj = self.collection.get_by_name(obj_name)
  5738. file_string = StringIO(obj.source_file)
  5739. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5740. with open(filename, 'w') as file:
  5741. file.writelines('G04*\n')
  5742. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  5743. (obj.kind.upper(), str(self.version), str(self.version_date)))
  5744. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  5745. file.writelines('G04 Created on : %s*\n' % time_string)
  5746. for line in file_string:
  5747. file.writelines(line)
  5748. def export_excellon(self, obj_name, filename, use_thread=True):
  5749. """
  5750. Exports a Excellon Object to an Excellon file.
  5751. :param filename: Path to the Excellon file to save to.
  5752. :return:
  5753. """
  5754. self.report_usage("export_excellon()")
  5755. if filename is None:
  5756. filename = self.defaults["global_last_save_folder"]
  5757. self.log.debug("export_excellon()")
  5758. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  5759. self.defaults["excellon_exp_decimals"]
  5760. )
  5761. units = ''
  5762. try:
  5763. obj = self.collection.get_by_name(str(obj_name))
  5764. except:
  5765. # TODO: The return behavior has not been established... should raise exception?
  5766. return "Could not retrieve object: %s" % obj_name
  5767. # updated units
  5768. eunits = self.defaults["excellon_exp_units"]
  5769. ewhole = self.defaults["excellon_exp_integer"]
  5770. efract = self.defaults["excellon_exp_decimals"]
  5771. ezeros = self.defaults["excellon_exp_zeros"]
  5772. eformat = self.defaults[ "excellon_exp_format"]
  5773. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5774. if fc_units == 'MM':
  5775. factor = 1 if eunits == 'METRIC' else 0.03937
  5776. else:
  5777. factor = 25.4 if eunits == 'METRIC' else 1
  5778. def make_excellon():
  5779. try:
  5780. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5781. header = 'M48\n'
  5782. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  5783. (str(self.version), str(self.version_date))
  5784. header += ';Filename: %s' % str(obj_name) + '\n'
  5785. header += ';Created on : %s' % time_str + '\n'
  5786. if eformat == 'dec':
  5787. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor)
  5788. header += eunits + '\n'
  5789. for tool in obj.tools:
  5790. if eunits == 'METRIC':
  5791. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5792. tool=str(tool),
  5793. dec=2)
  5794. else:
  5795. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5796. tool=str(tool),
  5797. dec=4)
  5798. else:
  5799. if ezeros == 'LZ':
  5800. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  5801. form='ndec', e_zeros='LZ', factor=factor)
  5802. header += '%s,%s\n' % (eunits, 'LZ')
  5803. header += format_exc
  5804. for tool in obj.tools:
  5805. if eunits == 'METRIC':
  5806. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5807. tool=str(tool),
  5808. dec=2)
  5809. else:
  5810. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5811. tool=str(tool),
  5812. dec=4)
  5813. else:
  5814. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  5815. form='ndec', e_zeros='TZ', factor=factor)
  5816. header += '%s,%s\n' % (eunits, 'TZ')
  5817. header += format_exc
  5818. for tool in obj.tools:
  5819. if eunits == 'METRIC':
  5820. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5821. tool=str(tool),
  5822. dec=2)
  5823. else:
  5824. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5825. tool=str(tool),
  5826. dec=4)
  5827. header += '%\n'
  5828. footer = 'M30\n'
  5829. exported_excellon = header
  5830. exported_excellon += excellon_code
  5831. exported_excellon += footer
  5832. with open(filename, 'w') as fp:
  5833. fp.write(exported_excellon)
  5834. if self.defaults["global_open_style"] is False:
  5835. self.file_opened.emit("Excellon", filename)
  5836. self.file_saved.emit("Excellon", filename)
  5837. self.inform.emit(_("[success] Excellon file exported to %s") % filename)
  5838. except Exception as e:
  5839. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  5840. return 'fail'
  5841. if use_thread is True:
  5842. with self.proc_container.new(_("Exporting Excellon")) as proc:
  5843. def job_thread_exc(app_obj):
  5844. ret = make_excellon()
  5845. if ret == 'fail':
  5846. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  5847. return
  5848. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  5849. else:
  5850. ret = make_excellon()
  5851. if ret == 'fail':
  5852. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  5853. return
  5854. def export_gerber(self, obj_name, filename, use_thread=True):
  5855. """
  5856. Exports a Gerber Object to an Gerber file.
  5857. :param filename: Path to the Gerber file to save to.
  5858. :return:
  5859. """
  5860. self.report_usage("export_gerber()")
  5861. if filename is None:
  5862. filename = self.defaults["global_last_save_folder"]
  5863. self.log.debug("export_gerber()")
  5864. try:
  5865. obj = self.collection.get_by_name(str(obj_name))
  5866. except:
  5867. # TODO: The return behavior has not been established... should raise exception?
  5868. return "Could not retrieve object: %s" % obj_name
  5869. # updated units
  5870. gunits = self.defaults["gerber_exp_units"]
  5871. gwhole = self.defaults["gerber_exp_integer"]
  5872. gfract = self.defaults["gerber_exp_decimals"]
  5873. gzeros = self.defaults["gerber_exp_zeros"]
  5874. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5875. if fc_units == 'MM':
  5876. factor = 1 if gunits == 'MM' else 0.03937
  5877. else:
  5878. factor = 25.4 if gunits == 'MM' else 1
  5879. def make_gerber():
  5880. try:
  5881. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5882. header = 'G04*\n'
  5883. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  5884. (str(self.version), str(self.version_date))
  5885. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  5886. header += 'G04 Created on : %s*' % time_str + '\n'
  5887. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  5888. header += "%MO{units}*%\n".format(units=gunits)
  5889. for apid in obj.apertures:
  5890. if obj.apertures[apid]['type'] == 'C':
  5891. header += "%ADD{apid}{type},{size}*%\n".format(
  5892. apid=str(apid),
  5893. type='C',
  5894. size=(factor * obj.apertures[apid]['size'])
  5895. )
  5896. elif obj.apertures[apid]['type'] == 'R':
  5897. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  5898. apid=str(apid),
  5899. type='R',
  5900. width=(factor * obj.apertures[apid]['width']),
  5901. height=(factor * obj.apertures[apid]['height'])
  5902. )
  5903. elif obj.apertures[apid]['type'] == 'O':
  5904. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  5905. apid=str(apid),
  5906. type='O',
  5907. width=(factor * obj.apertures[apid]['width']),
  5908. height=(factor * obj.apertures[apid]['height'])
  5909. )
  5910. header += '\n'
  5911. # obsolete units but some software may need it
  5912. if gunits == 'IN':
  5913. header += 'G70*\n'
  5914. else:
  5915. header += 'G71*\n'
  5916. # Absolute Mode
  5917. header += 'G90*\n'
  5918. header += 'G01*\n'
  5919. # positive polarity
  5920. header += '%LPD*%\n'
  5921. footer = 'M02*\n'
  5922. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  5923. exported_gerber = header
  5924. exported_gerber += gerber_code
  5925. exported_gerber += footer
  5926. with open(filename, 'w') as fp:
  5927. fp.write(exported_gerber)
  5928. if self.defaults["global_open_style"] is False:
  5929. self.file_opened.emit("Gerber", filename)
  5930. self.file_saved.emit("Gerber", filename)
  5931. self.inform.emit(_("[success] Gerber file exported to %s") % filename)
  5932. except Exception as e:
  5933. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  5934. return 'fail'
  5935. if use_thread is True:
  5936. with self.proc_container.new(_("Exporting Gerber")) as proc:
  5937. def job_thread_exc(app_obj):
  5938. ret = make_gerber()
  5939. if ret == 'fail':
  5940. self.inform.emit(_('[ERROR_NOTCL] Could not export Gerber file.'))
  5941. return
  5942. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  5943. else:
  5944. ret = make_gerber()
  5945. if ret == 'fail':
  5946. self.inform.emit(_('[ERROR_NOTCL] Could not export Gerber file.'))
  5947. return
  5948. def export_dxf(self, obj_name, filename, use_thread=True):
  5949. """
  5950. Exports a Geometry Object to an DXF file.
  5951. :param filename: Path to the DXF file to save to.
  5952. :return:
  5953. """
  5954. self.report_usage("export_dxf()")
  5955. if filename is None:
  5956. filename = self.defaults["global_last_save_folder"]
  5957. self.log.debug("export_dxf()")
  5958. format_exc = ''
  5959. units = ''
  5960. try:
  5961. obj = self.collection.get_by_name(str(obj_name))
  5962. except:
  5963. # TODO: The return behavior has not been established... should raise exception?
  5964. return "Could not retrieve object: %s" % obj_name
  5965. # updated units
  5966. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5967. if units == 'IN' or units == 'INCH':
  5968. units = 'INCH'
  5969. elif units == 'MM' or units == 'METIRC':
  5970. units ='METRIC'
  5971. def make_dxf():
  5972. try:
  5973. dxf_code = obj.export_dxf()
  5974. dxf_code.saveas(filename)
  5975. if self.defaults["global_open_style"] is False:
  5976. self.file_opened.emit("DXF", filename)
  5977. self.file_saved.emit("DXF", filename)
  5978. self.inform.emit(_("[success] DXF file exported to %s") % filename)
  5979. except:
  5980. return 'fail'
  5981. if use_thread is True:
  5982. with self.proc_container.new(_("Exporting DXF")) as proc:
  5983. def job_thread_exc(app_obj):
  5984. ret = make_dxf()
  5985. if ret == 'fail':
  5986. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  5987. return
  5988. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  5989. else:
  5990. ret = make_dxf()
  5991. if ret == 'fail':
  5992. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  5993. return
  5994. def import_svg(self, filename, geo_type='geometry', outname=None):
  5995. """
  5996. Adds a new Geometry Object to the projects and populates
  5997. it with shapes extracted from the SVG file.
  5998. :param filename: Path to the SVG file.
  5999. :param outname:
  6000. :return:
  6001. """
  6002. self.report_usage("import_svg()")
  6003. obj_type = ""
  6004. if geo_type is None or geo_type == "geometry":
  6005. obj_type = "geometry"
  6006. elif geo_type == "gerber":
  6007. obj_type = geo_type
  6008. else:
  6009. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  6010. "Only Geometry and Gerber are supported"))
  6011. return
  6012. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6013. def obj_init(geo_obj, app_obj):
  6014. geo_obj.import_svg(filename, obj_type, units=units)
  6015. geo_obj.multigeo = False
  6016. with self.proc_container.new(_("Importing SVG")) as proc:
  6017. # Object name
  6018. name = outname or filename.split('/')[-1].split('\\')[-1]
  6019. self.new_object(obj_type, name, obj_init, autoselected=False)
  6020. self.progress.emit(20)
  6021. # Register recent file
  6022. self.file_opened.emit("svg", filename)
  6023. # GUI feedback
  6024. self.inform.emit(_("[success] Opened: %s") % filename)
  6025. self.progress.emit(100)
  6026. def import_dxf(self, filename, geo_type='geometry', outname=None):
  6027. """
  6028. Adds a new Geometry Object to the projects and populates
  6029. it with shapes extracted from the DXF file.
  6030. :param filename: Path to the DXF file.
  6031. :param outname:
  6032. :type putname: str
  6033. :return:
  6034. """
  6035. self.report_usage("import_dxf()")
  6036. obj_type = ""
  6037. if geo_type is None or geo_type == "geometry":
  6038. obj_type = "geometry"
  6039. elif geo_type == "gerber":
  6040. obj_type = geo_type
  6041. else:
  6042. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  6043. "Only Geometry and Gerber are supported"))
  6044. return
  6045. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6046. def obj_init(geo_obj, app_obj):
  6047. geo_obj.import_dxf(filename, obj_type, units=units)
  6048. geo_obj.multigeo = False
  6049. with self.proc_container.new(_("Importing DXF")) as proc:
  6050. # Object name
  6051. name = outname or filename.split('/')[-1].split('\\')[-1]
  6052. self.new_object(obj_type, name, obj_init, autoselected=False)
  6053. self.progress.emit(20)
  6054. # Register recent file
  6055. self.file_opened.emit("dxf", filename)
  6056. # GUI feedback
  6057. self.inform.emit(_("[success] Opened: %s") % filename)
  6058. self.progress.emit(100)
  6059. def import_image(self, filename, type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  6060. """
  6061. Adds a new Geometry Object to the projects and populates
  6062. it with shapes extracted from the SVG file.
  6063. :param filename: Path to the SVG file.
  6064. :param outname:
  6065. :return:
  6066. """
  6067. self.report_usage("import_image()")
  6068. obj_type = ""
  6069. if type is None or type == "geometry":
  6070. obj_type = "geometry"
  6071. elif type == "gerber":
  6072. obj_type = type
  6073. else:
  6074. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  6075. "Only Geometry and Gerber are supported"))
  6076. return
  6077. def obj_init(geo_obj, app_obj):
  6078. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  6079. geo_obj.multigeo = False
  6080. with self.proc_container.new(_("Importing Image")) as proc:
  6081. # Object name
  6082. name = outname or filename.split('/')[-1].split('\\')[-1]
  6083. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  6084. self.new_object(obj_type, name, obj_init)
  6085. self.progress.emit(20)
  6086. # Register recent file
  6087. self.file_opened.emit("image", filename)
  6088. # GUI feedback
  6089. self.inform.emit(_("[success] Opened: %s") % filename)
  6090. self.progress.emit(100)
  6091. def open_gerber(self, filename, outname=None):
  6092. """
  6093. Opens a Gerber file, parses it and creates a new object for
  6094. it in the program. Thread-safe.
  6095. :param outname: Name of the resulting object. None causes the
  6096. name to be that of the file.
  6097. :param filename: Gerber file filename
  6098. :type filename: str
  6099. :param follow: If true, the parser will not create polygons, just lines
  6100. following the gerber path.
  6101. :type follow: bool
  6102. :return: None
  6103. """
  6104. # How the object should be initialized
  6105. def obj_init(gerber_obj, app_obj):
  6106. assert isinstance(gerber_obj, FlatCAMGerber), \
  6107. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  6108. # Opening the file happens here
  6109. self.progress.emit(30)
  6110. try:
  6111. gerber_obj.parse_file(filename)
  6112. except IOError:
  6113. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to open file: %s") % filename)
  6114. app_obj.progress.emit(0)
  6115. self.inform.emit(_('[ERROR_NOTCL] Failed to open file: %s') % filename)
  6116. return "fail"
  6117. except ParseError as err:
  6118. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to parse file: {name}. {error}").format(name=filename, error=str(err)))
  6119. app_obj.progress.emit(0)
  6120. self.log.error(str(err))
  6121. return "fail"
  6122. except:
  6123. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  6124. msg += traceback.format_exc()
  6125. app_obj.inform.emit(msg)
  6126. return "fail"
  6127. if gerber_obj.is_empty():
  6128. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  6129. # self.collection.set_active(gerber_obj.options["name"])
  6130. # self.collection.delete_active()
  6131. self.inform.emit(_("[ERROR_NOTCL] Object is not Gerber file or empty. Aborting object creation."))
  6132. return "fail"
  6133. # Further parsing
  6134. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  6135. App.log.debug("open_gerber()")
  6136. with self.proc_container.new(_("Opening Gerber")) as proc:
  6137. self.progress.emit(10)
  6138. # Object name
  6139. name = outname or filename.split('/')[-1].split('\\')[-1]
  6140. ### Object creation ###
  6141. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  6142. if ret == 'fail':
  6143. self.inform.emit(_('[ERROR_NOTCL] Open Gerber failed. Probable not a Gerber file.'))
  6144. return
  6145. # Register recent file
  6146. self.file_opened.emit("gerber", filename)
  6147. self.progress.emit(100)
  6148. # GUI feedback
  6149. self.inform.emit(_("[success] Opened: %s") % filename)
  6150. def open_excellon(self, filename, outname=None):
  6151. """
  6152. Opens an Excellon file, parses it and creates a new object for
  6153. it in the program. Thread-safe.
  6154. :param outname: Name of the resulting object. None causes the
  6155. name to be that of the file.
  6156. :param filename: Excellon file filename
  6157. :type filename: str
  6158. :return: None
  6159. """
  6160. App.log.debug("open_excellon()")
  6161. #self.progress.emit(10)
  6162. # How the object should be initialized
  6163. def obj_init(excellon_obj, app_obj):
  6164. # self.progress.emit(20)
  6165. try:
  6166. ret = excellon_obj.parse_file(filename=filename)
  6167. if ret == "fail":
  6168. log.debug("Excellon parsing failed.")
  6169. self.inform.emit(_("[ERROR_NOTCL] This is not Excellon file."))
  6170. return "fail"
  6171. except IOError:
  6172. app_obj.inform.emit(_("[ERROR_NOTCL] Cannot open file: %s") % filename)
  6173. log.debug("Could not open Excellon object.")
  6174. self.progress.emit(0) # TODO: self and app_bjj mixed
  6175. return "fail"
  6176. except:
  6177. msg = _("[ERROR_NOTCL] An internal error has occurred. See shell.\n")
  6178. msg += traceback.format_exc()
  6179. app_obj.inform.emit(msg)
  6180. return "fail"
  6181. ret = excellon_obj.create_geometry()
  6182. if ret == 'fail':
  6183. log.debug("Could not create geometry for Excellon object.")
  6184. return "fail"
  6185. # if excellon_obj.is_empty():
  6186. # app_obj.inform.emit("[ERROR_NOTCL] No geometry found in file: " + filename)
  6187. # return "fail"
  6188. for tool in excellon_obj.tools:
  6189. if excellon_obj.tools[tool]['solid_geometry']:
  6190. return
  6191. app_obj.inform.emit(_("[ERROR_NOTCL] No geometry found in file: %s") % filename)
  6192. return "fail"
  6193. with self.proc_container.new(_("Opening Excellon.")):
  6194. # Object name
  6195. name = outname or filename.split('/')[-1].split('\\')[-1]
  6196. ret = self.new_object("excellon", name, obj_init, autoselected=False)
  6197. if ret == 'fail':
  6198. self.inform.emit(_('[ERROR_NOTCL] Open Excellon file failed. Probable not an Excellon file.'))
  6199. return
  6200. # Register recent file
  6201. self.file_opened.emit("excellon", filename)
  6202. # GUI feedback
  6203. self.inform.emit(_("[success] Opened: %s") % filename)
  6204. # self.progress.emit(100)
  6205. def open_gcode(self, filename, outname=None):
  6206. """
  6207. Opens a G-gcode file, parses it and creates a new object for
  6208. it in the program. Thread-safe.
  6209. :param outname: Name of the resulting object. None causes the
  6210. name to be that of the file.
  6211. :param filename: G-code file filename
  6212. :type filename: str
  6213. :return: None
  6214. """
  6215. App.log.debug("open_gcode()")
  6216. # How the object should be initialized
  6217. def obj_init(job_obj, app_obj_):
  6218. """
  6219. :type app_obj_: App
  6220. """
  6221. assert isinstance(app_obj_, App), \
  6222. "Initializer expected App, got %s" % type(app_obj_)
  6223. self.progress.emit(10)
  6224. try:
  6225. f = open(filename)
  6226. gcode = f.read()
  6227. f.close()
  6228. except IOError:
  6229. app_obj_.inform.emit(_("[ERROR_NOTCL] Failed to open %s") % filename)
  6230. self.progress.emit(0)
  6231. return "fail"
  6232. job_obj.gcode = gcode
  6233. self.progress.emit(20)
  6234. ret = job_obj.gcode_parse()
  6235. if ret == "fail":
  6236. self.inform.emit(_("[ERROR_NOTCL] This is not GCODE"))
  6237. return "fail"
  6238. self.progress.emit(60)
  6239. job_obj.create_geometry()
  6240. with self.proc_container.new(_("Opening G-Code.")):
  6241. # Object name
  6242. name = outname or filename.split('/')[-1].split('\\')[-1]
  6243. # New object creation and file processing
  6244. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  6245. if ret == 'fail':
  6246. self.inform.emit(_("[ERROR_NOTCL] Failed to create CNCJob Object. Probable not a GCode file.\n "
  6247. "Attempting to create a FlatCAM CNCJob Object from "
  6248. "G-Code file failed during processing"))
  6249. return "fail"
  6250. # Register recent file
  6251. self.file_opened.emit("cncjob", filename)
  6252. # GUI feedback
  6253. self.inform.emit(_("[success] Opened: %s") % filename)
  6254. self.progress.emit(100)
  6255. def open_config_file(self, filename, run_from_arg=None):
  6256. """
  6257. Loads a config file from the specified file.
  6258. :param filename: Name of the file from which to load.
  6259. :type filename: str
  6260. :return: None
  6261. """
  6262. App.log.debug("Opening config file: " + filename)
  6263. # add the tab if it was closed
  6264. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  6265. # first clear previous text in text editor (if any)
  6266. self.ui.code_editor.clear()
  6267. # Switch plot_area to CNCJob tab
  6268. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  6269. try:
  6270. if filename:
  6271. f = QtCore.QFile(filename)
  6272. if f.open(QtCore.QIODevice.ReadOnly):
  6273. stream = QtCore.QTextStream(f)
  6274. gcode_edited = stream.readAll()
  6275. self.ui.code_editor.setPlainText(gcode_edited)
  6276. f.close()
  6277. except IOError:
  6278. App.log.error("Failed to open config file: %s" % filename)
  6279. self.inform.emit(_("[ERROR_NOTCL] Failed to open config file: %s") % filename)
  6280. return
  6281. def open_project(self, filename, run_from_arg=None):
  6282. """
  6283. Loads a project from the specified file.
  6284. 1) Loads and parses file
  6285. 2) Registers the file as recently opened.
  6286. 3) Calls on_file_new()
  6287. 4) Updates options
  6288. 5) Calls new_object() with the object's from_dict() as init method.
  6289. 6) Calls plot_all()
  6290. :param filename: Name of the file from which to load.
  6291. :type filename: str
  6292. :return: None
  6293. """
  6294. App.log.debug("Opening project: " + filename)
  6295. # Open and parse an uncompressed Project file
  6296. try:
  6297. f = open(filename, 'r')
  6298. except IOError:
  6299. App.log.error("Failed to open project file: %s" % filename)
  6300. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  6301. return
  6302. try:
  6303. d = json.load(f, object_hook=dict2obj)
  6304. except:
  6305. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s" % filename)
  6306. f.close()
  6307. # Open and parse a compressed Project file
  6308. try:
  6309. with lzma.open(filename) as f:
  6310. file_content = f.read().decode('utf-8')
  6311. d = json.loads(file_content, object_hook=dict2obj)
  6312. except IOError:
  6313. App.log.error("Failed to open project file: %s" % filename)
  6314. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  6315. return
  6316. self.file_opened.emit("project", filename)
  6317. # Clear the current project
  6318. ## NOT THREAD SAFE ##
  6319. if run_from_arg is True:
  6320. pass
  6321. else:
  6322. self.on_file_new()
  6323. #Project options
  6324. self.options.update(d['options'])
  6325. self.project_filename = filename
  6326. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  6327. self.set_screen_units(self.options["units"])
  6328. # Re create objects
  6329. App.log.debug("Re-creating objects...")
  6330. for obj in d['objs']:
  6331. def obj_init(obj_inst, app_inst):
  6332. obj_inst.from_dict(obj)
  6333. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  6334. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  6335. self.plot_all()
  6336. self.inform.emit(_("[success] Project loaded from: %s") % filename)
  6337. self.should_we_save = False
  6338. App.log.debug("Project loaded")
  6339. def propagate_defaults(self, silent=False):
  6340. """
  6341. This method is used to set default values in classes. It's
  6342. an alternative to project options but allows the use
  6343. of values invisible to the user.
  6344. :return: None
  6345. """
  6346. if silent is False:
  6347. self.log.debug("propagate_defaults()")
  6348. # Which objects to update the given parameters.
  6349. routes = {
  6350. "global_zdownrate": CNCjob,
  6351. "excellon_zeros": Excellon,
  6352. "excellon_format_upper_in": Excellon,
  6353. "excellon_format_lower_in": Excellon,
  6354. "excellon_format_upper_mm": Excellon,
  6355. "excellon_format_lower_mm": Excellon,
  6356. "excellon_units": Excellon,
  6357. "gerber_use_buffer_for_union": Gerber,
  6358. "geometry_multidepth": Geometry
  6359. }
  6360. for param in routes:
  6361. if param in routes[param].defaults:
  6362. try:
  6363. routes[param].defaults[param] = self.defaults[param]
  6364. if silent is False:
  6365. self.log.debug(" " + param + " OK")
  6366. except KeyError:
  6367. if silent is False:
  6368. self.log.debug(" ERROR: " + param + " not in defaults.")
  6369. else:
  6370. # Try extracting the name:
  6371. # classname_param here is param in the object
  6372. if param.find(routes[param].__name__.lower() + "_") == 0:
  6373. p = param[len(routes[param].__name__) + 1:]
  6374. if p in routes[param].defaults:
  6375. routes[param].defaults[p] = self.defaults[param]
  6376. if silent is False:
  6377. self.log.debug(" " + param + " OK!")
  6378. def restore_main_win_geom(self):
  6379. try:
  6380. self.ui.setGeometry(self.defaults["global_def_win_x"],
  6381. self.defaults["global_def_win_y"],
  6382. self.defaults["global_def_win_w"],
  6383. self.defaults["global_def_win_h"])
  6384. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  6385. settings = QSettings("Open Source", "FlatCAM")
  6386. if settings.contains("maximized_gui"):
  6387. maximized_ui = settings.value('maximized_gui', type=bool)
  6388. if maximized_ui is True:
  6389. self.ui.showMaximized()
  6390. except KeyError as e:
  6391. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  6392. def plot_all(self, zoom=True):
  6393. """
  6394. Re-generates all plots from all objects.
  6395. :return: None
  6396. """
  6397. self.log.debug("Plot_all()")
  6398. for obj in self.collection.get_list():
  6399. def worker_task(obj):
  6400. with self.proc_container.new("Plotting"):
  6401. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  6402. if zoom:
  6403. self.object_plotted.emit(obj)
  6404. # Send to worker
  6405. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  6406. # self.progress.emit(10)
  6407. #
  6408. # def worker_task(app_obj):
  6409. # print "worker task"
  6410. # percentage = 0.1
  6411. # try:
  6412. # delta = 0.9 / len(self.collection.get_list())
  6413. # except ZeroDivisionError:
  6414. # self.progress.emit(0)
  6415. # return
  6416. # for obj in self.collection.get_list():
  6417. # with self.proc_container.new("Plotting"):
  6418. # obj.plot()
  6419. # app_obj.object_plotted.emit(obj)
  6420. #
  6421. # percentage += delta
  6422. # self.progress.emit(int(percentage*100))
  6423. #
  6424. # self.progress.emit(0)
  6425. # self.plots_updated.emit()
  6426. #
  6427. # # Send to worker
  6428. # #self.worker.add_task(worker_task, [self])
  6429. # self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  6430. def register_folder(self, filename):
  6431. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  6432. def register_save_folder(self, filename):
  6433. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  6434. def set_progress_bar(self, percentage, text=""):
  6435. self.ui.progress_bar.setValue(int(percentage))
  6436. def setup_shell(self):
  6437. """
  6438. Creates shell functions. Runs once at startup.
  6439. :return: None
  6440. """
  6441. self.log.debug("setup_shell()")
  6442. def shelp(p=None):
  6443. if not p:
  6444. return _("Available commands:\n") + \
  6445. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  6446. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  6447. if p not in commands:
  6448. return "Unknown command: %s" % p
  6449. return commands[p]["help"]
  6450. # --- Migrated to new architecture ---
  6451. # def options(name):
  6452. # ops = self.collection.get_by_name(str(name)).options
  6453. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  6454. def h(*args):
  6455. """
  6456. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  6457. and standalone parameters into list.
  6458. """
  6459. kwa = {}
  6460. a = []
  6461. n = len(args)
  6462. name = None
  6463. for i in range(n):
  6464. match = re.search(r'^-([a-zA-Z].*)', args[i])
  6465. if match:
  6466. assert name is None
  6467. name = match.group(1)
  6468. continue
  6469. if name is None:
  6470. a.append(args[i])
  6471. else:
  6472. kwa[name] = args[i]
  6473. name = None
  6474. return a, kwa
  6475. @contextmanager
  6476. def wait_signal(signal, timeout=10000):
  6477. """
  6478. Block loop until signal emitted, timeout (ms) elapses
  6479. or unhandled exception happens in a thread.
  6480. :param signal: Signal to wait for.
  6481. """
  6482. loop = QtCore.QEventLoop()
  6483. # Normal termination
  6484. signal.connect(loop.quit)
  6485. # Termination by exception in thread
  6486. self.thread_exception.connect(loop.quit)
  6487. status = {'timed_out': False}
  6488. def report_quit():
  6489. status['timed_out'] = True
  6490. loop.quit()
  6491. yield
  6492. # Temporarily change how exceptions are managed.
  6493. oeh = sys.excepthook
  6494. ex = []
  6495. def except_hook(type_, value, traceback_):
  6496. ex.append(value)
  6497. oeh(type_, value, traceback_)
  6498. sys.excepthook = except_hook
  6499. # Terminate on timeout
  6500. if timeout is not None:
  6501. QtCore.QTimer.singleShot(timeout, report_quit)
  6502. #### Block ####
  6503. loop.exec_()
  6504. # Restore exception management
  6505. sys.excepthook = oeh
  6506. if ex:
  6507. self.raiseTclError(str(ex[0]))
  6508. if status['timed_out']:
  6509. raise Exception('Timed out!')
  6510. def make_docs():
  6511. output = ''
  6512. import collections
  6513. od = collections.OrderedDict(sorted(commands.items()))
  6514. for cmd_, val in od.items():
  6515. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  6516. t = val['help']
  6517. usage_i = t.find('>')
  6518. if usage_i < 0:
  6519. expl = t
  6520. output += expl + '\n\n'
  6521. continue
  6522. expl = t[:usage_i - 1]
  6523. output += expl + '\n\n'
  6524. end_usage_i = t[usage_i:].find('\n')
  6525. if end_usage_i < 0:
  6526. end_usage_i = len(t[usage_i:])
  6527. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  6528. else:
  6529. extras = t[usage_i+end_usage_i+1:]
  6530. parts = [s.strip() for s in extras.split('\n')]
  6531. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  6532. for p in parts:
  6533. output += ' ' + p + '\n\n'
  6534. return output
  6535. '''
  6536. Howto implement TCL shell commands:
  6537. All parameters passed to command should be possible to set as None and test it afterwards.
  6538. This is because we need to see error caused in tcl,
  6539. if None value as default parameter is not allowed TCL will return empty error.
  6540. Use:
  6541. def mycommand(name=None,...):
  6542. Test it like this:
  6543. if name is None:
  6544. self.raise_tcl_error('Argument name is missing.')
  6545. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  6546. otherwise we will miss it and processing will silently continue.
  6547. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  6548. which is catched in exec_command and displayed in TCL shell console with red background.
  6549. Error in console is displayed with TCL trace.
  6550. This behavior works only within main thread,
  6551. errors with promissed tasks can be catched and detected only with log.
  6552. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for TCL shell.
  6553. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  6554. '''
  6555. commands = {
  6556. 'help': {
  6557. 'fcn': shelp,
  6558. 'help': _("Shows list of commands.")
  6559. },
  6560. }
  6561. # Import/overwrite tcl commands as objects of TclCommand descendants
  6562. # This modifies the variable 'commands'.
  6563. tclCommands.register_all_commands(self, commands)
  6564. # Add commands to the tcl interpreter
  6565. for cmd in commands:
  6566. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  6567. # Make the tcl puts function return instead of print to stdout
  6568. self.tcl.eval('''
  6569. rename puts original_puts
  6570. proc puts {args} {
  6571. if {[llength $args] == 1} {
  6572. return "[lindex $args 0]"
  6573. } else {
  6574. eval original_puts $args
  6575. }
  6576. }
  6577. ''')
  6578. def setup_recent_items(self):
  6579. # TODO: Move this to constructor
  6580. icons = {
  6581. "gerber": "share/flatcam_icon16.png",
  6582. "excellon": "share/drill16.png",
  6583. 'geometry': "share/geometry16.png",
  6584. "cncjob": "share/cnc16.png",
  6585. "project": "share/project16.png",
  6586. "svg": "share/geometry16.png",
  6587. "dxf": "share/dxf16.png",
  6588. "pdf": "share/pdf32.png",
  6589. "image": "share/image16.png"
  6590. }
  6591. openers = {
  6592. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  6593. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  6594. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  6595. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  6596. 'project': self.open_project,
  6597. 'svg': self.import_svg,
  6598. 'dxf': self.import_dxf,
  6599. 'image': self.import_image,
  6600. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  6601. }
  6602. # Open file
  6603. try:
  6604. f = open(self.data_path + '/recent.json')
  6605. except IOError:
  6606. App.log.error("Failed to load recent item list.")
  6607. self.inform.emit(_("[ERROR_NOTCL] Failed to load recent item list."))
  6608. return
  6609. try:
  6610. self.recent = json.load(f)
  6611. except json.scanner.JSONDecodeError:
  6612. App.log.error("Failed to parse recent item list.")
  6613. self.inform.emit(_("[ERROR_NOTCL] Failed to parse recent item list."))
  6614. f.close()
  6615. return
  6616. f.close()
  6617. # Closure needed to create callbacks in a loop.
  6618. # Otherwise late binding occurs.
  6619. def make_callback(func, fname):
  6620. def opener():
  6621. func(fname)
  6622. return opener
  6623. def reset_recent():
  6624. # Reset menu
  6625. self.ui.recent.clear()
  6626. self.recent = []
  6627. try:
  6628. f = open(self.data_path + '/recent.json', 'w')
  6629. except IOError:
  6630. App.log.error("Failed to open recent items file for writing.")
  6631. return
  6632. json.dump(self.recent, f)
  6633. # Reset menu
  6634. self.ui.recent.clear()
  6635. # Create menu items
  6636. for recent in self.recent:
  6637. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  6638. try:
  6639. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  6640. # Attach callback
  6641. o = make_callback(openers[recent["kind"]], recent['filename'])
  6642. action.triggered.connect(o)
  6643. self.ui.recent.addAction(action)
  6644. except KeyError:
  6645. App.log.error("Unsupported file type: %s" % recent["kind"])
  6646. # Last action in Recent Files menu is one that Clear the content
  6647. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), "Clear Recent files", self)
  6648. clear_action.triggered.connect(reset_recent)
  6649. self.ui.recent.addSeparator()
  6650. self.ui.recent.addAction(clear_action)
  6651. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  6652. # self.ui.menufilerecent.set_submenu(recent_menu)
  6653. # recent_menu.show_all()
  6654. # self.ui.recent.show()
  6655. self.log.debug("Recent items list has been populated.")
  6656. def setup_component_editor(self):
  6657. # label = QtWidgets.QLabel("Choose an item from Project")
  6658. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  6659. sel_title = QtWidgets.QTextEdit(
  6660. _('<b>Shortcut Key List</b>'))
  6661. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  6662. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  6663. # font = self.sel_title.font()
  6664. # font.setPointSize(12)
  6665. # self.sel_title.setFont(font)
  6666. selected_text = _('''
  6667. <p><span style="font-size:14px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  6668. <p><span style="font-size:10px"><strong>Details</strong>:<br />
  6669. The normal flow when working in FlatCAM is the following:</span></p>
  6670. <ol>
  6671. <li><span style="font-size:10px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the menu&#39;s, toolbars, key shortcuts or even dragging and dropping the files on the GUI.<br />
  6672. <br />
  6673. You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  6674. &nbsp;</li>
  6675. <li><span style="font-size:10px">Once an object is available in the Project Tab, by selecting it and then focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  6676. <br />
  6677. If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong> is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate it even if it was out of focus.<br />
  6678. <br />
  6679. You can change the parameters in this screen and the flow direction is like this:<br />
  6680. <br />
  6681. <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  6682. </ol>
  6683. <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: <strng>F3</strong>.</span></p>
  6684. ''')
  6685. sel_title.setText(selected_text)
  6686. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6687. self.ui.selected_scroll_area.setWidget(sel_title)
  6688. # tool_title = QtWidgets.QTextEdit(
  6689. # '<b>Shortcut Key List</b>')
  6690. # tool_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  6691. # tool_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  6692. # # font = self.sel_title.font()
  6693. # # font.setPointSize(12)
  6694. # # self.sel_title.setFont(font)
  6695. #
  6696. # tool_text = '''
  6697. # <p><span style="font-size:14px"><strong>Tool Tab - Choose an Item in Tools Menu</strong></span></p>
  6698. #
  6699. # <p><span style="font-size:10px"><strong>Details</strong>:<br />
  6700. # Some of the functionality of FlatCAM have been implemented as tools (a sort of plugins). </span></p>
  6701. #
  6702. # <p><span style="font-size:10px">Most of the tools are accessible through&nbsp;the Tools menu or by using the associated shortcut keys.<br />
  6703. # Each such a tool, if it needs an object to be used as a source it will provide the way to select this object(s) through a series of comboboxes. The result of using a tool is either a Geometry, an information that can be used in the app or it can be a file that can be saved.</span></p>
  6704. #
  6705. # <ol>
  6706. # </ol>
  6707. #
  6708. # <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: &#39;`&#39; (key left to 1).</span></p>
  6709. #
  6710. # '''
  6711. #
  6712. # tool_title.setText(tool_text)
  6713. # tool_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6714. #
  6715. # self.ui.tool_scroll_area.setWidget(tool_title)
  6716. def setup_obj_classes(self):
  6717. """
  6718. Sets up application specifics on the FlatCAMObj class.
  6719. :return: None
  6720. """
  6721. FlatCAMObj.app = self
  6722. ObjectCollection.app = self
  6723. FCProcess.app = self
  6724. FCProcessContainer.app = self
  6725. def version_check(self):
  6726. """
  6727. Checks for the latest version of the program. Alerts the
  6728. user if theirs is outdated. This method is meant to be run
  6729. in a separate thread.
  6730. :return: None
  6731. """
  6732. self.log.debug("version_check()")
  6733. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  6734. full_url = App.version_url + \
  6735. "?s=" + str(self.defaults['global_serial']) + \
  6736. "&v=" + str(self.version) + \
  6737. "&os=" + str(self.os) + \
  6738. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  6739. else:
  6740. # no_stats dict; just so it won't break things on website
  6741. no_ststs_dict = {}
  6742. no_ststs_dict["global_ststs"] = {}
  6743. full_url = App.version_url + \
  6744. "?s=" + str(self.defaults['global_serial']) + \
  6745. "&v=" + str(self.version) + \
  6746. "&os=" + str(self.os) + \
  6747. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  6748. App.log.debug("Checking for updates @ %s" % full_url)
  6749. ### Get the data
  6750. try:
  6751. f = urllib.request.urlopen(full_url)
  6752. except:
  6753. # App.log.warning("Failed checking for latest version. Could not connect.")
  6754. self.log.warning("Failed checking for latest version. Could not connect.")
  6755. self.inform.emit(_("[WARNING_NOTCL] Failed checking for latest version. Could not connect."))
  6756. return
  6757. try:
  6758. data = json.load(f)
  6759. except Exception as e:
  6760. App.log.error("Could not parse information about latest version.")
  6761. self.inform.emit(_("[ERROR_NOTCL] Could not parse information about latest version."))
  6762. App.log.debug("json.load(): %s" % str(e))
  6763. f.close()
  6764. return
  6765. f.close()
  6766. ### Latest version?
  6767. if self.version >= data["version"]:
  6768. App.log.debug("FlatCAM is up to date!")
  6769. self.inform.emit(_("[success] FlatCAM is up to date!"))
  6770. return
  6771. App.log.debug("Newer version available.")
  6772. self.message.emit(
  6773. _("Newer Version Available"),
  6774. _("There is a newer version of FlatCAM available for download:\n\n") +
  6775. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  6776. _("info")
  6777. )
  6778. def on_zoom_fit(self, event):
  6779. """
  6780. Callback for zoom-out request. This can be either from the corresponding
  6781. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  6782. with axes limits from the geometry bounds of all objects.
  6783. :param event: Ignored.
  6784. :return: None
  6785. """
  6786. self.plotcanvas.fit_view()
  6787. def disable_all_plots(self):
  6788. self.report_usage("disable_all_plots()")
  6789. self.disable_plots(self.collection.get_list())
  6790. self.inform.emit(_("[success] All plots disabled."))
  6791. def disable_other_plots(self):
  6792. self.report_usage("disable_other_plots()")
  6793. self.disable_plots(self.collection.get_non_selected())
  6794. self.inform.emit(_("[success] All non selected plots disabled."))
  6795. def enable_all_plots(self):
  6796. self.report_usage("enable_all_plots()")
  6797. self.enable_plots(self.collection.get_list())
  6798. self.inform.emit(_("[success] All plots enabled."))
  6799. # TODO: FIX THIS
  6800. '''
  6801. By default this is not threaded
  6802. If threaded the app give warnings like this:
  6803. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  6804. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  6805. '''
  6806. def enable_plots(self, objects, threaded=True):
  6807. if threaded is True:
  6808. def worker_task(app_obj):
  6809. # percentage = 0.1
  6810. # try:
  6811. # delta = 0.9 / len(objects)
  6812. # except ZeroDivisionError:
  6813. # self.progress.emit(0)
  6814. # return
  6815. for obj in objects:
  6816. obj.options['plot'] = True
  6817. # percentage += delta
  6818. # self.progress.emit(int(percentage*100))
  6819. # self.progress.emit(0)
  6820. self.plots_updated.emit()
  6821. # self.collection.update_view()
  6822. # Send to worker
  6823. # self.worker.add_task(worker_task, [self])
  6824. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  6825. else:
  6826. for obj in objects:
  6827. obj.options['plot'] = True
  6828. # self.progress.emit(0)
  6829. self.plots_updated.emit()
  6830. # self.collection.update_view()
  6831. # TODO: FIX THIS
  6832. '''
  6833. By default this is not threaded
  6834. If threaded the app give warnings like this:
  6835. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  6836. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  6837. '''
  6838. def disable_plots(self, objects, threaded=True):
  6839. # TODO: This method is very similar to replot_all. Try to merge.
  6840. """
  6841. Disables plots
  6842. :param objects: list
  6843. Objects to be disabled
  6844. :return:
  6845. """
  6846. if threaded is True:
  6847. # self.progress.emit(10)
  6848. def worker_task(app_obj):
  6849. # percentage = 0.1
  6850. # try:
  6851. # delta = 0.9 / len(objects)
  6852. # except ZeroDivisionError:
  6853. # self.progress.emit(0)
  6854. # return
  6855. for obj in objects:
  6856. obj.options['plot'] = False
  6857. # percentage += delta
  6858. # self.progress.emit(int(percentage*100))
  6859. # self.progress.emit(0)
  6860. self.plots_updated.emit()
  6861. # self.collection.update_view()
  6862. # Send to worker
  6863. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  6864. else:
  6865. for obj in objects:
  6866. obj.options['plot'] = False
  6867. self.plots_updated.emit()
  6868. # self.collection.update_view()
  6869. def clear_plots(self):
  6870. objects = self.collection.get_list()
  6871. for obj in objects:
  6872. obj.clear(obj == objects[-1])
  6873. # Clear pool to free memory
  6874. self.clear_pool()
  6875. def generate_cnc_job(self, objects):
  6876. self.report_usage("generate_cnc_job()")
  6877. # for obj in objects:
  6878. # obj.generatecncjob()
  6879. for obj in objects:
  6880. obj.on_generatecnc_button_click()
  6881. def save_project(self, filename, quit=False):
  6882. """
  6883. Saves the current project to the specified file.
  6884. :param filename: Name of the file in which to save.
  6885. :type filename: str
  6886. :return: None
  6887. """
  6888. self.log.debug("save_project()")
  6889. self.save_in_progress = True
  6890. with self.proc_container.new(_("Saving FlatCAM Project")) as proc:
  6891. ## Capture the latest changes
  6892. # Current object
  6893. try:
  6894. self.collection.get_active().read_form()
  6895. except:
  6896. self.log.debug("There was no active object")
  6897. pass
  6898. # Project options
  6899. self.options_read_form()
  6900. # Serialize the whole project
  6901. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  6902. "options": self.options,
  6903. "version": self.version}
  6904. if self.defaults["global_save_compressed"] is True:
  6905. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  6906. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  6907. # # Write
  6908. f.write(g)
  6909. self.inform.emit(_("[success] Project saved to: %s") % filename)
  6910. else:
  6911. # Open file
  6912. try:
  6913. f = open(filename, 'w')
  6914. except IOError:
  6915. App.log.error("Failed to open file for saving: %s", filename)
  6916. return
  6917. # Write
  6918. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  6919. f.close()
  6920. # verification of the saved project
  6921. # Open and parse
  6922. try:
  6923. saved_f = open(filename, 'r')
  6924. except IOError:
  6925. self.inform.emit(_("[ERROR_NOTCL] Failed to verify project file: %s. Retry to save it.") % filename)
  6926. return
  6927. try:
  6928. saved_d = json.load(saved_f, object_hook=dict2obj)
  6929. except:
  6930. self.inform.emit(
  6931. _("[ERROR_NOTCL] Failed to parse saved project file: %s. Retry to save it.") % filename)
  6932. f.close()
  6933. return
  6934. saved_f.close()
  6935. if 'version' in saved_d:
  6936. self.inform.emit(_("[success] Project saved to: %s") % filename)
  6937. else:
  6938. self.inform.emit(_("[ERROR_NOTCL] Failed to save project file: %s. Retry to save it.") % filename)
  6939. # if quit:
  6940. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  6941. # t.start()
  6942. self.start_delayed_quit(delay=500, filename=filename, quit=quit)
  6943. def start_delayed_quit(self, delay, filename, quit=None):
  6944. """
  6945. :param delay: period of checking if project file size is more than zero; in seconds
  6946. :param filename: the name of the project file to be checked periodically for size more than zero
  6947. :return:
  6948. """
  6949. to_quit = quit
  6950. self.save_timer = QtCore.QTimer()
  6951. self.save_timer.setInterval(delay)
  6952. self.save_timer.timeout.connect(lambda : self.check_project_file_size(filename=filename, quit=to_quit))
  6953. self.save_timer.start()
  6954. def check_project_file_size(self, filename, quit=None):
  6955. """
  6956. :param filename: the name of the project file to be checked periodically for size more than zero
  6957. :return:
  6958. """
  6959. try:
  6960. if os.stat(filename).st_size > 0:
  6961. self.save_in_progress = False
  6962. self.save_timer.stop()
  6963. if quit:
  6964. self.app_quit.emit()
  6965. except Exception:
  6966. traceback.print_exc()
  6967. def on_options_app2project(self):
  6968. """
  6969. Callback for Options->Transfer Options->App=>Project. Copies options
  6970. from application defaults to project defaults.
  6971. :return: None
  6972. """
  6973. self.report_usage("on_options_app2project")
  6974. self.defaults_read_form()
  6975. self.options.update(self.defaults)
  6976. self.options_write_form()
  6977. def on_options_project2app(self):
  6978. """
  6979. Callback for Options->Transfer Options->Project=>App. Copies options
  6980. from project defaults to application defaults.
  6981. :return: None
  6982. """
  6983. self.report_usage("on_options_project2app")
  6984. self.options_read_form()
  6985. self.defaults.update(self.options)
  6986. self.defaults_write_form()
  6987. def on_options_project2object(self):
  6988. """
  6989. Callback for Options->Transfer Options->Project=>Object. Copies options
  6990. from project defaults to the currently selected object.
  6991. :return: None
  6992. """
  6993. self.report_usage("on_options_project2object")
  6994. self.options_read_form()
  6995. obj = self.collection.get_active()
  6996. if obj is None:
  6997. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6998. return
  6999. for option in self.options:
  7000. if option.find(obj.kind + "_") == 0:
  7001. oname = option[len(obj.kind) + 1:]
  7002. obj.options[oname] = self.options[option]
  7003. obj.to_form() # Update UI
  7004. def on_options_object2project(self):
  7005. """
  7006. Callback for Options->Transfer Options->Object=>Project. Copies options
  7007. from the currently selected object to project defaults.
  7008. :return: None
  7009. """
  7010. self.report_usage("on_options_object2project")
  7011. obj = self.collection.get_active()
  7012. if obj is None:
  7013. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7014. return
  7015. obj.read_form()
  7016. for option in obj.options:
  7017. if option in ['name']: # TODO: Handle this better...
  7018. continue
  7019. self.options[obj.kind + "_" + option] = obj.options[option]
  7020. self.options_write_form()
  7021. def on_options_object2app(self):
  7022. """
  7023. Callback for Options->Transfer Options->Object=>App. Copies options
  7024. from the currently selected object to application defaults.
  7025. :return: None
  7026. """
  7027. self.report_usage("on_options_object2app")
  7028. obj = self.collection.get_active()
  7029. if obj is None:
  7030. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7031. return
  7032. obj.read_form()
  7033. for option in obj.options:
  7034. if option in ['name']: # TODO: Handle this better...
  7035. continue
  7036. self.defaults[obj.kind + "_" + option] = obj.options[option]
  7037. self.defaults_write_form()
  7038. def on_options_app2object(self):
  7039. """
  7040. Callback for Options->Transfer Options->App=>Object. Copies options
  7041. from application defaults to the currently selected object.
  7042. :return: None
  7043. """
  7044. self.report_usage("on_options_app2object")
  7045. self.defaults_read_form()
  7046. obj = self.collection.get_active()
  7047. if obj is None:
  7048. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7049. return
  7050. for option in self.defaults:
  7051. if option.find(obj.kind + "_") == 0:
  7052. oname = option[len(obj.kind) + 1:]
  7053. obj.options[oname] = self.defaults[option]
  7054. obj.to_form() # Update UI
  7055. # end of file